User:Sethalves/scheme-perceptron

From Noisebridge
Jump to: navigation, search
#!/usr/bin/guile \
--debug -s
!#


(use-modules (ice-9 format))


(define (dot-product v0 v1)
  (apply + (map (lambda (m0 m1) (* m0 m1)) v0 v1)))


(define (sigmoid beta x)
  ;; sigmoid (beta, x) = 1/(1+e^(-beta*x))
  (/ 1.0 (+ 1.0 (exp (* x (- 0.0 beta))))))


(define (sigmoid-1 x)
  (sigmoid 1.0 x))


(define (perceptron)
  (let ((inputs (list (list 1 0 0) (list 1 0 1) (list 1 1 0) (list 1 1 1)))
        (answers (list 1 1 1 0))
        (weights (list 0.0 0.0 0.0)))
    (format #t "inputs : ~a~%" inputs)
    (format #t "answers : ~a~%" answers)
    (format #t "starting weights : ~a~%" weights)
    (format #t "ending weights : ~a~%"
            (mainfunc inputs answers weights))
    ))


(define (mainfunc inputs answers weights)
  ;; (format #t "weights : ~a~%" weights)
  (let ((checked (check-all-inputs inputs weights answers)))
    (if (equal? checked weights)
        weights
        (mainfunc inputs answers checked))))


(define (check-all-inputs inputs weights answers)
  (let loop ((inputs inputs)
             (weights weights)
             (answers answers))
    (if (null? inputs) weights
        (loop (cdr inputs)
              (adjust-weights (car inputs) weights (car answers))
              (cdr answers)))))


(define (adjust-weights inputs weights answer)
  (let* ((got (sigmoid-1 (dot-product inputs weights)))
         (err (- answer got)))
    (map (lambda (input weight)
           (* (+ weight (* err 0.1)) input))
         inputs
         weights)))

(perceptron)

Personal tools