memoizing the neighbors function over graphs
[neural-net.git] / src / neural_net / som.clj
blob068341dd9f941a6c7df1d7ba0de5b38f4c41cebf
1 (ns neural-net.som                      ; Kohonen maps
2   (:use neural-net.core)
3   (:use clojure.set))
5 (defn self-organizing-map:run
6   "Return a map of the dot product of each neurons weight against x" [this x]
7   (reduce (fn [a [k v]] (cons [k (reduce + (map * x (v :weights)))] a))
8           [] (get (this :map) :vertices)))
10 (defn self-organizing-map:learn
11   "Return a map of learning spread through the map." [this x y d]
12   (let [winner (first (first (reverse (sort-by second (or y (run this x))))))]
13     (reduce (fn [a [n d]] (assoc a n ((this :update) this d n x)))
14             {} (get (this :nn) winner))))
16 (defn self-organizing-map:train [this delta]
17   (assoc this
18     :map (neural-net.core.Graph.
19           (reduce (fn [a [k d]] (assoc a
20                                  k {:weights (map + d ((get a k) :weights))}))
21                   (get (this :map) :vertices) delta)
22           (get (this :map) :edges))))
24 (comment                                ; train a self organizing map
25   (let [som-g (neural-net.core.Graph.
26                {:a {:weights [ 1  0]}
27                 :b {:weights [ 0  1]}
28                 :c {:weights [-1  0]}
29                 :d {:weights [ 0 -1]}}
30                [[:a :b] [:b :c] [:c :d]])
31         som {:phi self-organizing-map:run
32              :learn self-organizing-map:learn
33              :train self-organizing-map:train
34              :eta 1
35              :update (fn [this dist n x]
36                        (map (fn [x] (* (/ x (inc dist)) (this :eta)))
37                             (map -
38                                  x (((get (this :map) :vertices) n) :weights))))
39              :map som-g
40              :nn (nearest-neighbors som-g)}]
41     (first (train som [0.8 0.2] nil nil)))
42   ;; =>
43   ;; {:d (0.2 0.3),  :c (0.6 0.06666666666666667),
44   ;;  :b (0.4 -0.4), :a (-0.19999999999999996 0.2)}  
45   )