getting started on a DSL approach
[neural-net.git] / neural_net / core.clj
blobb78cbb32110b914400888bcb1c2dfcdaf0b6c4a9
1 (ns neural-net.core
2   (:use [neural-net.util])
3   (:use [clojure.contrib math]))
5 ;;; Value-based DSL definition
6 (defprotocol NeuralValue
7   (spec      [this]   "Returns the specification of the net.")
8   (func      [this]   "Returns a function implementing the neural net.")
9   (train     [this f] "Trains the net using f returning the updated version."))
11 (defrecord Neural [spec]
12   NeuralValue
13   (func [this] (func spec))
14   (spec [this] spec))
16 (defn net [spec]
17   "Create and return a Neural network based on the specification."
18   (Neural. spec))
20 (extend-protocol
21  NeuralValue
22  ;; a map holds the values of a neuron
23  clojure.lang.IPersistentMap
24  (spec [this] this)
25  (func [this] 48)
26  (train [this] this)
27  ;; ordered lists holding collections of neurons
28  clojure.lang.ISeq
29  clojure.lang.IPersistentVector
30  (spec [this] (vec (map spec this)))
31  (func [this] )
32  (train [this] )
33  ;; TODO need to notice matrices of numbers as neurons specifications
34  ;; java.lang.Double
35  ;; java.lang.Integer
36  ;; can't resolve weight assignment for unordered collections
37  ;; clojure.lang.PersistentHashSet
38  )
40 ;;; activation functions
41 (def d-step
42      ^{:doc   "Derivative of the step function."}
43      (fn [v] (if (= v 0) (/ 1 0) 0)))
45 (def step
46      ^{:doc   "The sigmoid function."
47        :deriv d-step}
48      (fn [v] (if (pos? v) 1 -1)))
50 (def d-sigmoid
51      ^{:doc   "Derivative of the sigmoid function."}
52      (fn [v] (/ (expt Math/E (- 0 v)) (expt (+ (expt Math/E (- 0 v)) 1) 2))))
54 (def sigmoid
55      ^{:doc   "The sigmoid function."
56        :deriv d-sigmoid}
57      (fn [v] (/ 1 (+ 1 (expt Math/E (- 0 v))))))