neuralnetwork.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. /*
  2. * MIT License
  3. *
  4. * Copyright (c) 2019 Alexey Edelev <semlanik@gmail.com>
  5. *
  6. * This file is part of NeuralNetwork project https://git.semlanik.org/semlanik/NeuralNetwork
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy of this
  9. * software and associated documentation files (the "Software"), to deal in the Software
  10. * without restriction, including without limitation the rights to use, copy, modify,
  11. * merge, publish, distribute, sublicense, and/or sell copies of the Software, and
  12. * to permit persons to whom the Software is furnished to do so, subject to the following
  13. * conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all copies
  16. * or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  19. * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  20. * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  21. * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  23. * DEALINGS IN THE SOFTWARE.
  24. */
  25. package neuralnetworkbase
  26. import (
  27. "errors"
  28. "fmt"
  29. teach "../teach"
  30. mat "gonum.org/v1/gonum/mat"
  31. )
  32. // NeuralNetwork is simple neural network implementation
  33. //
  34. // Resources:
  35. // http://neuralnetworksanddeeplearning.com
  36. // https://www.youtube.com/watch?v=fNk_zzaMoSs
  37. //
  38. // Matrix: A
  39. // Description: A is set of calculated neuron activations after sigmoid correction
  40. // Format: 0 n N
  41. // ⎡A[0] ⎤ ... ⎡A[0] ⎤ ... ⎡A[0] ⎤
  42. // ⎢A[1] ⎥ ... ⎢A[1] ⎥ ... ⎢A[1] ⎥
  43. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  44. // ⎢A[i] ⎥ ... ⎢A[i] ⎥ ... ⎢A[i] ⎥
  45. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  46. // ⎣A[s] ⎦ ... ⎣A[s] ⎦ ... ⎣A[s] ⎦
  47. // Where s = Sizes[n], N = len(Sizes)
  48. //
  49. // Matrix: Z
  50. // Description: Z is set of calculated raw neuron activations
  51. // Format: 0 n N
  52. // ⎡Z[0] ⎤ ... ⎡Z[0] ⎤ ... ⎡Z[0] ⎤
  53. // ⎢Z[1] ⎥ ... ⎢Z[1] ⎥ ... ⎢Z[1] ⎥
  54. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  55. // ⎢Z[i] ⎥ ... ⎢Z[i] ⎥ ... ⎢Z[i] ⎥
  56. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  57. // ⎣Z[s] ⎦ ... ⎣Z[s] ⎦ ... ⎣Z[s] ⎦
  58. // Where s = Sizes[n], N = len(Sizes)
  59. //
  60. // Matrix: Biases
  61. // Description: Biases is set of biases per layer except L0
  62. // Format:
  63. // ⎡b[0] ⎤
  64. // ⎢b[1] ⎥
  65. // ⎢ ... ⎥
  66. // ⎢b[i] ⎥
  67. // ⎢ ... ⎥
  68. // ⎣b[s] ⎦
  69. // Where s = Sizes[n]
  70. //
  71. // Matrix: Weights
  72. // Description: Weights is set of weights per layer except L0
  73. // Format:
  74. // ⎡w[0,0] ... w[0,j] ... w[0,s']⎤
  75. // ⎢w[1,0] ... w[1,j] ... w[1,s']⎥
  76. // ⎢ ... ⎥
  77. // ⎢w[i,0] ... w[i,j] ... w[i,s']⎥
  78. // ⎢ ... ⎥
  79. // ⎣w[s,0] ... w[s,j] ... w[s,s']⎦
  80. // Where s = Sizes[n], s' = Sizes[n-1]
  81. type NeuralNetwork struct {
  82. Count int
  83. Sizes []int
  84. Biases []*mat.Dense
  85. Weights []*mat.Dense
  86. A []*mat.Dense
  87. Z []*mat.Dense
  88. alpha float64
  89. trainingCycles int
  90. }
  91. func NewNeuralNetwork(sizes []int, nu float64, trainingCycles int) (nn *NeuralNetwork, err error) {
  92. err = nil
  93. if len(sizes) < 3 {
  94. fmt.Printf("Invalid network configuration: %v\n", sizes)
  95. return nil, errors.New("Invalid network configuration: %v\n")
  96. }
  97. for i := 0; i < len(sizes); i++ {
  98. if sizes[i] < 2 {
  99. fmt.Printf("Invalid network configuration: %v\n", sizes)
  100. return nil, errors.New("Invalid network configuration: %v\n")
  101. }
  102. }
  103. if nu <= 0.0 || nu > 1.0 {
  104. fmt.Printf("Invalid η value: %v\n", nu)
  105. return nil, errors.New("Invalid η value: %v\n")
  106. }
  107. if trainingCycles <= 0 {
  108. fmt.Printf("Invalid training cycles number: %v\n", trainingCycles)
  109. return nil, errors.New("Invalid training cycles number: %v\n")
  110. }
  111. if trainingCycles < 100 {
  112. fmt.Println("Training cycles number probably is too small")
  113. }
  114. nn = &NeuralNetwork{}
  115. nn.Sizes = sizes
  116. nn.Count = len(sizes)
  117. nn.Weights = make([]*mat.Dense, nn.Count)
  118. nn.Biases = make([]*mat.Dense, nn.Count)
  119. nn.A = make([]*mat.Dense, nn.Count)
  120. nn.Z = make([]*mat.Dense, nn.Count)
  121. nn.alpha = nu / float64(nn.Sizes[0])
  122. nn.trainingCycles = trainingCycles
  123. for i := 1; i < nn.Count; i++ {
  124. nn.Weights[i] = generateRandomDense(nn.Sizes[i], nn.Sizes[i-1])
  125. nn.Biases[i] = generateRandomDense(nn.Sizes[i], 1)
  126. }
  127. return
  128. }
  129. func (nn *NeuralNetwork) Predict(aIn mat.Matrix) (maxIndex int, max float64) {
  130. r, _ := aIn.Dims()
  131. if r != nn.Sizes[0] {
  132. fmt.Printf("Invalid rows number of input matrix size: %v\n", r)
  133. return -1, 0.0
  134. }
  135. nn.forward(aIn)
  136. result := nn.result()
  137. r, _ = result.Dims()
  138. max = 0.0
  139. maxIndex = 0
  140. for i := 0; i < r; i++ {
  141. if result.At(i, 0) > max {
  142. max = result.At(i, 0)
  143. maxIndex = i
  144. }
  145. }
  146. return
  147. }
  148. func (nn *NeuralNetwork) Teach(teacher teach.Teacher) {
  149. for i := 0; i < nn.trainingCycles; i++ {
  150. for teacher.Next() {
  151. nn.backward(teacher.GetData(), teacher.GetExpect())
  152. }
  153. }
  154. }
  155. func (nn *NeuralNetwork) SaveState(filename string) {
  156. }
  157. func (nn *NeuralNetwork) LoadState(filename string) {
  158. }
  159. func (nn *NeuralNetwork) forward(aIn mat.Matrix) {
  160. nn.A[0] = mat.DenseCopyOf(aIn)
  161. for i := 1; i < nn.Count; i++ {
  162. nn.A[i] = mat.NewDense(nn.Sizes[i], 1, nil)
  163. aSrc := nn.A[i-1]
  164. aDst := nn.A[i]
  165. // Each iteration implements formula bellow for neuron activation values
  166. // A[l]=σ(W[l]*A[l−1]+B[l])
  167. // W[l]*A[l−1]
  168. aDst.Mul(nn.Weights[i], aSrc)
  169. // W[l]*A[l−1]+B[l]
  170. aDst.Add(aDst, nn.Biases[i])
  171. // Save raw activation value for back propagation
  172. nn.Z[i] = mat.DenseCopyOf(aDst)
  173. // σ(W[l]*A[l−1]+B[l])
  174. aDst.Apply(applySigmoid, aDst)
  175. }
  176. }
  177. func (nn *NeuralNetwork) backward(aIn, aOut mat.Matrix) {
  178. nn.forward(aIn)
  179. lastLayerNum := nn.Count - 1
  180. // To calculate new values of weights and biases
  181. // following formulas are used:
  182. // W[l] = A[l−1]*δ[l]
  183. // B[l] = δ[l]
  184. // For last layer δ value is calculated by following:
  185. // δ = (A[L]−y)⊙σ'(Z[L])
  186. // Calculate initial error for last layer L
  187. // error = A[L]-y
  188. // Where y is expected activations set
  189. err := &mat.Dense{}
  190. err.Sub(nn.result(), aOut)
  191. // Calculate sigmoids prime σ'(Z[L]) for last layer L
  192. sigmoidsPrime := &mat.Dense{}
  193. sigmoidsPrime.Apply(applySigmoidPrime, nn.Z[lastLayerNum])
  194. // (A[L]−y)⊙σ'(Z[L])
  195. delta := &mat.Dense{}
  196. delta.MulElem(err, sigmoidsPrime)
  197. // B[L] = δ[L]
  198. biases := mat.DenseCopyOf(delta)
  199. // W[L] = A[L−1]*δ[L]
  200. weights := &mat.Dense{}
  201. weights.Mul(delta, nn.A[lastLayerNum-1].T())
  202. // Initialize new weights and biases values with last layer values
  203. newBiases := []*mat.Dense{makeBackGradient(biases, nn.Biases[lastLayerNum], nn.alpha)}
  204. newWeights := []*mat.Dense{makeBackGradient(weights, nn.Weights[lastLayerNum], nn.alpha)}
  205. // Save calculated delta value temporary error variable
  206. err = delta
  207. // Next layer Weights and Biases are calculated using same formulas:
  208. // W[l] = A[l−1]*δ[l]
  209. // B[l] = δ[l]
  210. // But δ[l] is calculated using different formula:
  211. // δ[l] = ((Wt[l+1])*δ[l+1])⊙σ'(Z[l])
  212. // Where Wt[l+1] is transposed matrix of actual Weights from
  213. // forward step
  214. for l := nn.Count - 2; l > 0; l-- {
  215. // Calculate sigmoids prime σ'(Z[l]) for last layer l
  216. sigmoidsPrime := &mat.Dense{}
  217. sigmoidsPrime.Apply(applySigmoidPrime, nn.Z[l])
  218. // (Wt[l+1])*δ[l+1]
  219. // err bellow is delta from previous step(l+1)
  220. delta := &mat.Dense{}
  221. wdelta := &mat.Dense{}
  222. wdelta.Mul(nn.Weights[l+1].T(), err)
  223. // Calculate new delta and store it to temporary variable err
  224. // δ[l] = ((Wt[l+1])*δ[l+1])⊙σ'(Z[l])
  225. delta.MulElem(wdelta, sigmoidsPrime)
  226. err = delta
  227. // B[l] = δ[l]
  228. biases := mat.DenseCopyOf(delta)
  229. // W[l] = A[l−1]*δ[l]
  230. // At this point it's required to give explanation for inaccuracy
  231. // in the formula
  232. // Multiplying of activations matrix for layer l-1 and δ[l] is imposible
  233. // because view of matrices are following:
  234. // A[l-1] δ[l]
  235. // ⎡A[0] ⎤ ⎡δ[0] ⎤
  236. // ⎢A[1] ⎥ ⎢δ[1] ⎥
  237. // ⎢ ... ⎥ ⎢ ... ⎥
  238. // ⎢A[i] ⎥ X ⎢δ[i] ⎥
  239. // ⎢ ... ⎥ ⎢ ... ⎥
  240. // ⎣A[s'] ⎦ ⎣δ[s] ⎦
  241. // So we need to modify these matrices to apply mutiplications and got
  242. // Weights matrix of following view:
  243. // ⎡w[0,0] ... w[0,j] ... w[0,s']⎤
  244. // ⎢w[1,0] ... w[1,j] ... w[1,s']⎥
  245. // ⎢ ... ⎥
  246. // ⎢w[i,0] ... w[i,j] ... w[i,s']⎥
  247. // ⎢ ... ⎥
  248. // ⎣w[s,0] ... w[s,j] ... w[s,s']⎦
  249. // So we swap matrices and transpose A[l-1] to get valid multiplication
  250. // of following view:
  251. // δ[l] A[l-1]
  252. // ⎡δ[0] ⎤ x [A[0] A[1] ... A[i] ... A[s']]
  253. // ⎢δ[1] ⎥
  254. // ⎢ ... ⎥
  255. // ⎢δ[i] ⎥
  256. // ⎢ ... ⎥
  257. // ⎣δ[s] ⎦
  258. weights := &mat.Dense{}
  259. weights.Mul(delta, nn.A[l-1].T())
  260. // !Prepend! new Biases and Weights
  261. newBiases = append([]*mat.Dense{makeBackGradient(biases, nn.Biases[l], nn.alpha)}, newBiases...)
  262. newWeights = append([]*mat.Dense{makeBackGradient(weights, nn.Weights[l], nn.alpha)}, newWeights...)
  263. }
  264. newBiases = append([]*mat.Dense{&mat.Dense{}}, newBiases...)
  265. newWeights = append([]*mat.Dense{&mat.Dense{}}, newWeights...)
  266. nn.Biases = newBiases
  267. nn.Weights = newWeights
  268. }
  269. func (nn *NeuralNetwork) result() *mat.Dense {
  270. return nn.A[nn.Count-1]
  271. }