neuralnetwork.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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 l L
  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[l] - Neural network layer size
  48. // L = len(Sizes) - Number of neural network layers
  49. //
  50. // Matrix: Z
  51. // Description: Z is set of calculated raw neuron activations
  52. // Format: 0 l L
  53. // ⎡Z[0] ⎤ ... ⎡Z[0] ⎤ ... ⎡Z[0] ⎤
  54. // ⎢Z[1] ⎥ ... ⎢Z[1] ⎥ ... ⎢Z[1] ⎥
  55. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  56. // ⎢Z[i] ⎥ ... ⎢Z[i] ⎥ ... ⎢Z[i] ⎥
  57. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  58. // ⎣Z[s] ⎦ ... ⎣Z[s] ⎦ ... ⎣Z[s] ⎦
  59. // Where s = Sizes[l] - Neural network layer size
  60. // L = len(Sizes) - Number of neural network layers
  61. //
  62. // Matrix: Biases
  63. // Description: Biases is set of biases per layer except l0
  64. // NOTE: l0 is always empty Dense because first layer
  65. // doesn't have connections to previous layer
  66. // Format: 1 l L
  67. // ⎡b[0] ⎤ ... ⎡b[0] ⎤ ... ⎡b[0] ⎤
  68. // ⎢b[1] ⎥ ... ⎢b[1] ⎥ ... ⎢b[1] ⎥
  69. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  70. // ⎢b[i] ⎥ ... ⎢b[i] ⎥ ... ⎢b[i] ⎥
  71. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  72. // ⎣b[s] ⎦ ... ⎣b[s] ⎦ ... ⎣b[s] ⎦
  73. // Where s = Sizes[l] - Neural network layer size
  74. // L = len(Sizes) - Number of neural network layers
  75. //
  76. // Matrix: Weights
  77. // Description: Weights is set of weights per layer except l0
  78. // NOTE: l0 is always empty Dense because first layer
  79. // doesn't have connections to previous layer
  80. // Format: 1 l L
  81. // ⎡w[0,0] ... w[0,j] ... w[0,s']⎤ ... ⎡w[0,0] ... w[0,j] ... w[0,s']⎤ ... ⎡w[0,0] ... w[0,j] ... w[0,s']⎤
  82. // ⎢w[1,0] ... w[1,j] ... w[1,s']⎥ ... ⎢w[1,0] ... w[1,j] ... w[1,s']⎥ ... ⎢w[1,0] ... w[1,j] ... w[1,s']⎥
  83. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  84. // ⎢w[i,0] ... w[i,j] ... w[i,s']⎥ ... ⎢w[i,0] ... w[i,j] ... w[i,s']⎥ ... ⎢w[i,0] ... w[i,j] ... w[i,s']⎥
  85. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  86. // ⎣w[s,0] ... w[s,j] ... w[s,s']⎦ ... ⎣w[s,0] ... w[s,j] ... w[s,s']⎦ ... ⎣w[s,0] ... w[s,j] ... w[s,s']⎦
  87. // Where s = Sizes[l] - Neural network layer size
  88. // s' = Sizes[l-1] - Previous neural network layer size
  89. // L = len(Sizes) - Number of neural network layers
  90. type NeuralNetwork struct {
  91. Count int
  92. Sizes []int
  93. Biases []*mat.Dense
  94. Weights []*mat.Dense
  95. A []*mat.Dense
  96. Z []*mat.Dense
  97. alpha float64
  98. trainingCycles int
  99. }
  100. func NewNeuralNetwork(sizes []int, nu float64, trainingCycles int) (nn *NeuralNetwork, err error) {
  101. err = nil
  102. if len(sizes) < 3 {
  103. fmt.Printf("Invalid network configuration: %v\n", sizes)
  104. return nil, errors.New("Invalid network configuration: %v\n")
  105. }
  106. for i := 0; i < len(sizes); i++ {
  107. if sizes[i] < 2 {
  108. fmt.Printf("Invalid network configuration: %v\n", sizes)
  109. return nil, errors.New("Invalid network configuration: %v\n")
  110. }
  111. }
  112. if nu <= 0.0 || nu > 1.0 {
  113. fmt.Printf("Invalid η value: %v\n", nu)
  114. return nil, errors.New("Invalid η value: %v\n")
  115. }
  116. if trainingCycles <= 0 {
  117. fmt.Printf("Invalid training cycles number: %v\n", trainingCycles)
  118. return nil, errors.New("Invalid training cycles number: %v\n")
  119. }
  120. if trainingCycles < 100 {
  121. fmt.Println("Training cycles number probably is too small")
  122. }
  123. nn = &NeuralNetwork{}
  124. nn.Sizes = sizes
  125. nn.Count = len(sizes)
  126. nn.Weights = make([]*mat.Dense, nn.Count)
  127. nn.Biases = make([]*mat.Dense, nn.Count)
  128. nn.A = make([]*mat.Dense, nn.Count)
  129. nn.Z = make([]*mat.Dense, nn.Count)
  130. nn.alpha = nu / float64(nn.Sizes[0])
  131. nn.trainingCycles = trainingCycles
  132. for i := 1; i < nn.Count; i++ {
  133. nn.Weights[i] = generateRandomDense(nn.Sizes[i], nn.Sizes[i-1])
  134. nn.Biases[i] = generateRandomDense(nn.Sizes[i], 1)
  135. }
  136. return
  137. }
  138. func (nn *NeuralNetwork) Copy() (out *NeuralNetwork) {
  139. out = &NeuralNetwork{}
  140. out.Sizes = nn.Sizes
  141. out.Count = nn.Count
  142. out.Weights = make([]*mat.Dense, nn.Count)
  143. out.Biases = make([]*mat.Dense, nn.Count)
  144. out.A = make([]*mat.Dense, nn.Count)
  145. out.Z = make([]*mat.Dense, nn.Count)
  146. out.alpha = nn.alpha
  147. out.trainingCycles = nn.trainingCycles
  148. for i := 1; i < out.Count; i++ {
  149. nn.Weights[i] = mat.DenseCopyOf(out.Weights[i])
  150. nn.Biases[i] = mat.DenseCopyOf(out.Biases[i])
  151. }
  152. return
  153. }
  154. func (nn *NeuralNetwork) Predict(aIn mat.Matrix) (maxIndex int, max float64) {
  155. r, _ := aIn.Dims()
  156. if r != nn.Sizes[0] {
  157. fmt.Printf("Invalid rows number of input matrix size: %v\n", r)
  158. return -1, 0.0
  159. }
  160. nn.forward(aIn)
  161. result := nn.result()
  162. r, _ = result.Dims()
  163. max = 0.0
  164. maxIndex = 0
  165. for i := 0; i < r; i++ {
  166. if result.At(i, 0) > max {
  167. max = result.At(i, 0)
  168. maxIndex = i
  169. }
  170. }
  171. return
  172. }
  173. func (nn *NeuralNetwork) Teach(teacher teach.Teacher) {
  174. for i := 0; i < nn.trainingCycles; i++ {
  175. for teacher.NextData() {
  176. nn.backward(teacher.GetData())
  177. }
  178. }
  179. }
  180. func (nn *NeuralNetwork) SaveState(filename string) {
  181. }
  182. func (nn *NeuralNetwork) LoadState(filename string) {
  183. }
  184. func (nn *NeuralNetwork) forward(aIn mat.Matrix) {
  185. nn.A[0] = mat.DenseCopyOf(aIn)
  186. for i := 1; i < nn.Count; i++ {
  187. nn.A[i] = mat.NewDense(nn.Sizes[i], 1, nil)
  188. aSrc := nn.A[i-1]
  189. aDst := nn.A[i]
  190. // Each iteration implements formula bellow for neuron activation values
  191. // A[l]=σ(W[l]*A[l−1]+B[l])
  192. // W[l]*A[l−1]
  193. aDst.Mul(nn.Weights[i], aSrc)
  194. // W[l]*A[l−1]+B[l]
  195. aDst.Add(aDst, nn.Biases[i])
  196. // Save raw activation value for back propagation
  197. nn.Z[i] = mat.DenseCopyOf(aDst)
  198. // σ(W[l]*A[l−1]+B[l])
  199. aDst.Apply(applySigmoid, aDst)
  200. }
  201. }
  202. func (nn *NeuralNetwork) backward(aIn, aOut mat.Matrix) {
  203. nn.forward(aIn)
  204. lastLayerNum := nn.Count - 1
  205. // To calculate new values of weights and biases
  206. // following formulas are used:
  207. // W[l] = A[l−1]*δ[l]
  208. // B[l] = δ[l]
  209. // For last layer δ value is calculated by following:
  210. // δ = (A[L]−y)⊙σ'(Z[L])
  211. // Calculate initial error for last layer L
  212. // error = A[L]-y
  213. // Where y is expected activations set
  214. err := &mat.Dense{}
  215. err.Sub(nn.result(), aOut)
  216. // Calculate sigmoids prime σ'(Z[L]) for last layer L
  217. sigmoidsPrime := &mat.Dense{}
  218. sigmoidsPrime.Apply(applySigmoidPrime, nn.Z[lastLayerNum])
  219. // (A[L]−y)⊙σ'(Z[L])
  220. delta := &mat.Dense{}
  221. delta.MulElem(err, sigmoidsPrime)
  222. // B[L] = δ[L]
  223. biases := mat.DenseCopyOf(delta)
  224. // W[L] = A[L−1]*δ[L]
  225. weights := &mat.Dense{}
  226. weights.Mul(delta, nn.A[lastLayerNum-1].T())
  227. // Initialize new weights and biases values with last layer values
  228. newBiases := []*mat.Dense{makeBackGradient(biases, nn.Biases[lastLayerNum], nn.alpha)}
  229. newWeights := []*mat.Dense{makeBackGradient(weights, nn.Weights[lastLayerNum], nn.alpha)}
  230. // Save calculated delta value temporary error variable
  231. err = delta
  232. // Next layer Weights and Biases are calculated using same formulas:
  233. // W[l] = A[l−1]*δ[l]
  234. // B[l] = δ[l]
  235. // But δ[l] is calculated using different formula:
  236. // δ[l] = ((Wt[l+1])*δ[l+1])⊙σ'(Z[l])
  237. // Where Wt[l+1] is transposed matrix of actual Weights from
  238. // forward step
  239. for l := nn.Count - 2; l > 0; l-- {
  240. // Calculate sigmoids prime σ'(Z[l]) for last layer l
  241. sigmoidsPrime := &mat.Dense{}
  242. sigmoidsPrime.Apply(applySigmoidPrime, nn.Z[l])
  243. // (Wt[l+1])*δ[l+1]
  244. // err bellow is delta from previous step(l+1)
  245. delta := &mat.Dense{}
  246. wdelta := &mat.Dense{}
  247. wdelta.Mul(nn.Weights[l+1].T(), err)
  248. // Calculate new delta and store it to temporary variable err
  249. // δ[l] = ((Wt[l+1])*δ[l+1])⊙σ'(Z[l])
  250. delta.MulElem(wdelta, sigmoidsPrime)
  251. err = delta
  252. // B[l] = δ[l]
  253. biases := mat.DenseCopyOf(delta)
  254. // W[l] = A[l−1]*δ[l]
  255. // At this point it's required to give explanation for inaccuracy
  256. // in the formula
  257. // Multiplying of activations matrix for layer l-1 and δ[l] is imposible
  258. // because view of matrices are following:
  259. // A[l-1] δ[l]
  260. // ⎡A[0] ⎤ ⎡δ[0] ⎤
  261. // ⎢A[1] ⎥ ⎢δ[1] ⎥
  262. // ⎢ ... ⎥ ⎢ ... ⎥
  263. // ⎢A[i] ⎥ X ⎢δ[i] ⎥
  264. // ⎢ ... ⎥ ⎢ ... ⎥
  265. // ⎣A[s'] ⎦ ⎣δ[s] ⎦
  266. // So we need to modify these matrices to apply mutiplications and got
  267. // Weights matrix of following view:
  268. // ⎡w[0,0] ... w[0,j] ... w[0,s']⎤
  269. // ⎢w[1,0] ... w[1,j] ... w[1,s']⎥
  270. // ⎢ ... ⎥
  271. // ⎢w[i,0] ... w[i,j] ... w[i,s']⎥
  272. // ⎢ ... ⎥
  273. // ⎣w[s,0] ... w[s,j] ... w[s,s']⎦
  274. // So we swap matrices and transpose A[l-1] to get valid multiplication
  275. // of following view:
  276. // δ[l] A[l-1]
  277. // ⎡δ[0] ⎤ x [A[0] A[1] ... A[i] ... A[s']]
  278. // ⎢δ[1] ⎥
  279. // ⎢ ... ⎥
  280. // ⎢δ[i] ⎥
  281. // ⎢ ... ⎥
  282. // ⎣δ[s] ⎦
  283. weights := &mat.Dense{}
  284. weights.Mul(delta, nn.A[l-1].T())
  285. // !Prepend! new Biases and Weights
  286. newBiases = append([]*mat.Dense{makeBackGradient(biases, nn.Biases[l], nn.alpha)}, newBiases...)
  287. newWeights = append([]*mat.Dense{makeBackGradient(weights, nn.Weights[l], nn.alpha)}, newWeights...)
  288. }
  289. newBiases = append([]*mat.Dense{&mat.Dense{}}, newBiases...)
  290. newWeights = append([]*mat.Dense{&mat.Dense{}}, newWeights...)
  291. nn.Biases = newBiases
  292. nn.Weights = newWeights
  293. }
  294. func (nn *NeuralNetwork) result() *mat.Dense {
  295. return nn.A[nn.Count-1]
  296. }
  297. func (nn *NeuralNetwork) TeachResilient(aIn, aOut mat.Matrix, nuP, nuM float64, deltaMin, deltaMax float64) {
  298. }