splitting out the perceptron and back-propagation functions
[neural-net.git] / src / neural_net / back-propagation.clj
bloba44e3413e5def8b7c5ca556a7857c34b7cfb36c2
1 (ns neural-net.back-propagation
2   (:use neural-net.core))
4 (defn back-prop:run "Phi function for back propagation" [v]
5   {:v v :y v})
7 (defn back-prop:learn "Back propagation" [this x res d]
8   ((fn [gradient]
9      (vec (map
10            (fn [y w]
11              {:delta-w (* (this :eta) gradient y)
12               :weight w
13               :gradient gradient})
14            (map :y x) (this :weights))))
15    (if (and (map? d) (get d :desired))
16      (* (- (d :desired) (res :y))     ; output layer
17         ((this :d-phi) (res :v)))
18      (* ((this :d-phi) (get res :v 1)) ; hidden layer
19         (reduce + (map (fn [a] (* (a :gradient) (a :weight)))
20                        (if (vector? d) d (vec (list d)))))))))
22 (comment       ; learning binary representations with back-propagation
23   (let [n {:phi   back-prop:run
24            :d-phi (fn [_] 1)
25            :accum (comp (partial reduce +)
26                         (partial map (fn [x w] (* (x :y) w))))
27            :learn back-prop:learn
28            :train (fn [n delta] (assoc n :weights
29                                       (vec (map + (n :weights)
30                                                 (map :delta-w delta)))))
31            :eta 0.1
32            :weights [0.5 0.5 0.5]}
33         epic [[[0 0 0] 0]
34               [[0 0 1] 1]
35               [[0 1 0] 2]
36               [[0 1 1] 3]
37               [[1 0 0] 4]
38               [[1 0 1] 5]
39               [[1 1 0] 6]
40               [[1 1 1] 7]]
41         net [(repeat 3 n) n]
42         trained (reduce
43                  (fn [m _]
44                    (reduce
45                     (fn [n p]
46                       (let [x (vec (map (fn [el] {:y el}) (first p)))
47                             d {:desired (second p)}]
48                         ;; (println (format "x:%S->%S run:%S"
49                         ;;                  x (d :desired) ((run n x) :y)))
50                         (second (train n x (run n x) d))))
51                     m epic)) net (range 20))]
53     ;; converting binary to decimal
54     (map
55      (fn [p]
56        [(first p) (second p)
57         ((run trained (map (fn [el] {:y el}) (first p))) :y)])
58      epic))
59   ;; =>
60   ;; ([[0 0 0] 0 0.0]
61   ;;  [[0 0 1] 1 1.0000000325609912]
62   ;;  [[0 1 0] 2 2.0000000163062657]
63   ;;  [[0 1 1] 3 3.000000048867257]
64   ;;  [[1 0 0] 4 3.9999998651699054]
65   ;;  [[1 0 1] 5 4.999999897730897]
66   ;;  [[1 1 0] 6 5.999999881476171]
67   ;;  [[1 1 1] 7 6.999999914037161])  
68   )