neuralnetwork.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. /*
  2. * MIT License
  3. *
  4. * Copyright (c) 2019 Alexey Edelev <semlanik@gmail.com>, Tatyana Borisova <tanusshhka@mail.ru>
  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. "encoding/binary"
  28. "errors"
  29. "fmt"
  30. "io"
  31. teach "../teach"
  32. mat "gonum.org/v1/gonum/mat"
  33. )
  34. // NeuralNetwork is simple neural network implementation
  35. //
  36. // Resources:
  37. // http://neuralnetworksanddeeplearning.com
  38. // https://www.youtube.com/watch?v=fNk_zzaMoSs
  39. // http://www.inf.fu-berlin.de/lehre/WS06/Musterererkennung/Paper/rprop.pdf
  40. //
  41. // Matrix: A
  42. // Description: A is set of calculated neuron activations after sigmoid correction
  43. // Format: 0 l L
  44. // ⎡A[0] ⎤ ... ⎡A[0] ⎤ ... ⎡A[0] ⎤
  45. // ⎢A[1] ⎥ ... ⎢A[1] ⎥ ... ⎢A[1] ⎥
  46. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  47. // ⎢A[i] ⎥ ... ⎢A[i] ⎥ ... ⎢A[i] ⎥
  48. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  49. // ⎣A[s] ⎦ ... ⎣A[s] ⎦ ... ⎣A[s] ⎦
  50. // Where s = Sizes[l] - Neural network layer size
  51. // L = len(Sizes) - Number of neural network layers
  52. //
  53. // Matrix: Z
  54. // Description: Z is set of calculated raw neuron activations
  55. // Format: 0 l L
  56. // ⎡Z[0] ⎤ ... ⎡Z[0] ⎤ ... ⎡Z[0] ⎤
  57. // ⎢Z[1] ⎥ ... ⎢Z[1] ⎥ ... ⎢Z[1] ⎥
  58. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  59. // ⎢Z[i] ⎥ ... ⎢Z[i] ⎥ ... ⎢Z[i] ⎥
  60. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  61. // ⎣Z[s] ⎦ ... ⎣Z[s] ⎦ ... ⎣Z[s] ⎦
  62. // Where s = Sizes[l] - Neural network layer size
  63. // L = len(Sizes) - Number of neural network layers
  64. //
  65. // Matrix: Biases
  66. // Description: Biases is set of biases per layer except l0
  67. // NOTE: l0 is always empty Dense because first layer
  68. // doesn't have connections to previous layer
  69. // Format: 1 l L
  70. // ⎡b[0] ⎤ ... ⎡b[0] ⎤ ... ⎡b[0] ⎤
  71. // ⎢b[1] ⎥ ... ⎢b[1] ⎥ ... ⎢b[1] ⎥
  72. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  73. // ⎢b[i] ⎥ ... ⎢b[i] ⎥ ... ⎢b[i] ⎥
  74. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  75. // ⎣b[s] ⎦ ... ⎣b[s] ⎦ ... ⎣b[s] ⎦
  76. // Where s = Sizes[l] - Neural network layer size
  77. // L = len(Sizes) - Number of neural network layers
  78. //
  79. // Matrix: Weights
  80. // Description: Weights is set of weights per layer except l0
  81. // NOTE: l0 is always empty Dense because first layer
  82. // doesn't have connections to previous layer
  83. // Format: 1 l L
  84. // ⎡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']⎤
  85. // ⎢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']⎥
  86. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  87. // ⎢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']⎥
  88. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  89. // ⎣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']⎦
  90. // Where s = Sizes[l] - Neural network layer size
  91. // s' = Sizes[l-1] - Previous neural network layer size
  92. // L = len(Sizes) - Number of neural network layers
  93. type NeuralNetwork struct {
  94. LayerCount int
  95. Sizes []int
  96. Biases []*mat.Dense
  97. Weights []*mat.Dense
  98. A []*mat.Dense
  99. Z []*mat.Dense
  100. BGradient []interface{}
  101. WGradient []interface{}
  102. epocs int
  103. }
  104. func NewNeuralNetwork(sizes []int, epocs int, gradientDescentInitializer GradientDescentInitializer) (nn *NeuralNetwork, err error) {
  105. err = nil
  106. if len(sizes) < 3 {
  107. fmt.Printf("Invalid network configuration: %v\n", sizes)
  108. return nil, errors.New("Invalid network configuration: %v\n")
  109. }
  110. for i := 0; i < len(sizes); i++ {
  111. if sizes[i] < 2 {
  112. fmt.Printf("Invalid network configuration: %v\n", sizes)
  113. return nil, errors.New("Invalid network configuration: %v\n")
  114. }
  115. }
  116. if epocs <= 0 {
  117. fmt.Printf("Invalid training cycles number: %v\n", epocs)
  118. return nil, errors.New("Invalid training cycles number: %v\n")
  119. }
  120. if epocs < 100 {
  121. fmt.Println("Training cycles number probably is too small")
  122. }
  123. nn = &NeuralNetwork{}
  124. nn.Sizes = sizes
  125. nn.LayerCount = len(sizes)
  126. nn.Biases = make([]*mat.Dense, nn.LayerCount)
  127. nn.Weights = make([]*mat.Dense, nn.LayerCount)
  128. nn.BGradient = make([]interface{}, nn.LayerCount)
  129. nn.WGradient = make([]interface{}, nn.LayerCount)
  130. nn.A = make([]*mat.Dense, nn.LayerCount)
  131. nn.Z = make([]*mat.Dense, nn.LayerCount)
  132. nn.epocs = epocs
  133. for l := 1; l < nn.LayerCount; l++ {
  134. nn.Biases[l] = generateRandomDense(nn.Sizes[l], 1)
  135. nn.Weights[l] = generateRandomDense(nn.Sizes[l], nn.Sizes[l-1])
  136. nn.BGradient[l] = gradientDescentInitializer(nn, l, BiasGradient)
  137. nn.WGradient[l] = gradientDescentInitializer(nn, l, WeightGradient)
  138. }
  139. return
  140. }
  141. func (nn *NeuralNetwork) Copy() (out *NeuralNetwork) {
  142. out = &NeuralNetwork{}
  143. out.Sizes = nn.Sizes
  144. out.LayerCount = nn.LayerCount
  145. out.Weights = make([]*mat.Dense, nn.LayerCount)
  146. out.Biases = make([]*mat.Dense, nn.LayerCount)
  147. out.A = make([]*mat.Dense, nn.LayerCount)
  148. out.Z = make([]*mat.Dense, nn.LayerCount)
  149. out.epocs = nn.epocs
  150. for l := 1; l < out.LayerCount; l++ {
  151. out.Weights[l] = mat.DenseCopyOf(nn.Weights[l])
  152. out.Biases[l] = mat.DenseCopyOf(nn.Biases[l])
  153. }
  154. return
  155. }
  156. func (nn *NeuralNetwork) Predict(aIn mat.Matrix) (maxIndex int, max float64) {
  157. r, _ := aIn.Dims()
  158. if r != nn.Sizes[0] {
  159. fmt.Printf("Invalid rows number of input matrix size: %v\n", r)
  160. return -1, 0.0
  161. }
  162. nn.forward(aIn)
  163. result := nn.result()
  164. r, _ = result.Dims()
  165. max = 0.0
  166. maxIndex = 0
  167. for i := 0; i < r; i++ {
  168. if result.At(i, 0) > max {
  169. max = result.At(i, 0)
  170. maxIndex = i
  171. }
  172. }
  173. return
  174. }
  175. func (nn *NeuralNetwork) Teach(teacher teach.Teacher) {
  176. if _, ok := nn.WGradient[nn.LayerCount-1].(OnlineGradientDescent); ok {
  177. nn.TeachOnline(teacher)
  178. } else if _, ok := nn.WGradient[nn.LayerCount-1].(BatchGradientDescent); ok {
  179. nn.TeachBatch(teacher)
  180. } else {
  181. panic("Invalid gradient descent type")
  182. }
  183. }
  184. func (nn *NeuralNetwork) TeachOnline(teacher teach.Teacher) {
  185. for t := 0; t < nn.epocs; t++ {
  186. for teacher.NextData() {
  187. dB, dW := nn.backward(teacher.GetData())
  188. for l := 1; l < nn.LayerCount; l++ {
  189. bGradient, ok := nn.BGradient[l].(OnlineGradientDescent)
  190. if !ok {
  191. panic("bGradient is not a OnlineGradientDescent")
  192. }
  193. wGradient, ok := nn.WGradient[l].(OnlineGradientDescent)
  194. if !ok {
  195. panic("wGradient is not a OnlineGradientDescent")
  196. }
  197. nn.Biases[l] = bGradient.ApplyDelta(nn.Biases[l], dB[l])
  198. nn.Weights[l] = wGradient.ApplyDelta(nn.Weights[l], dW[l])
  199. }
  200. }
  201. teacher.Reset()
  202. }
  203. }
  204. func (nn *NeuralNetwork) TeachBatch(teacher teach.Teacher) {
  205. for t := 0; t < nn.epocs; t++ {
  206. for teacher.NextData() {
  207. dB, dW := nn.backward(teacher.GetData())
  208. for l := 1; l < nn.LayerCount; l++ {
  209. bGradient, ok := nn.BGradient[l].(BatchGradientDescent)
  210. if !ok {
  211. panic("bGradient is not a BatchGradientDescent")
  212. }
  213. wGradient, ok := nn.WGradient[l].(BatchGradientDescent)
  214. if !ok {
  215. panic("wGradient is not a BatchGradientDescent")
  216. }
  217. bGradient.AccumGradients(dB[l])
  218. wGradient.AccumGradients(dW[l])
  219. }
  220. }
  221. teacher.Reset()
  222. for l := 1; l < nn.LayerCount; l++ {
  223. bGradient := nn.BGradient[l].(BatchGradientDescent)
  224. wGradient := nn.WGradient[l].(BatchGradientDescent)
  225. nn.Biases[l] = bGradient.ApplyDelta(nn.Biases[l])
  226. nn.Weights[l] = wGradient.ApplyDelta(nn.Weights[l])
  227. }
  228. }
  229. }
  230. func (nn *NeuralNetwork) SaveState(writer io.Writer) {
  231. //save input array count
  232. bufferSize := make([]byte, 4)
  233. binary.LittleEndian.PutUint32(bufferSize[0:], uint32(nn.LayerCount))
  234. _, err := writer.Write(bufferSize)
  235. check(err)
  236. fmt.Printf("wrote value %d\n", uint32(nn.LayerCount))
  237. // save an input array
  238. buffer := make([]byte, nn.LayerCount*4)
  239. for i := 0; i < nn.LayerCount; i++ {
  240. binary.LittleEndian.PutUint32(buffer[i*4:], uint32(nn.Sizes[i]))
  241. }
  242. _, err = writer.Write(buffer)
  243. check(err)
  244. // fmt.Printf("wrote buffer %d bytes\n", n2)
  245. //save biases
  246. ////////////////////////
  247. for i := 1; i < nn.LayerCount; i++ {
  248. saveDense(writer, nn.Biases[i])
  249. }
  250. //save weights
  251. ////////////////////////
  252. for i := 1; i < nn.LayerCount; i++ {
  253. saveDense(writer, nn.Weights[i])
  254. }
  255. }
  256. func (nn *NeuralNetwork) LoadState(reader io.Reader) {
  257. // Reade count
  258. nn.LayerCount = readInt(reader)
  259. // Read an input array
  260. sizeBuffer := readByteArray(reader, nn.LayerCount*4)
  261. nn.Sizes = make([]int, nn.LayerCount)
  262. for i := 0; i < nn.LayerCount; i++ {
  263. nn.Sizes[i] = int(binary.LittleEndian.Uint32(sizeBuffer[i*4:]))
  264. // fmt.Printf("LoadState: nn.Sizes[%d] %d \n", i, nn.Sizes[i])
  265. }
  266. nn.Weights = []*mat.Dense{&mat.Dense{}}
  267. nn.Biases = []*mat.Dense{&mat.Dense{}}
  268. // read Biases
  269. nn.Biases[0] = &mat.Dense{}
  270. for i := 1; i < nn.LayerCount; i++ {
  271. nn.Biases = append(nn.Biases, &mat.Dense{})
  272. nn.Biases[i] = readDense(reader, nn.Biases[i])
  273. }
  274. // read Weights
  275. nn.Weights[0] = &mat.Dense{}
  276. for i := 1; i < nn.LayerCount; i++ {
  277. nn.Weights = append(nn.Weights, &mat.Dense{})
  278. nn.Weights[i] = readDense(reader, nn.Weights[i])
  279. }
  280. nn.A = make([]*mat.Dense, nn.LayerCount)
  281. nn.Z = make([]*mat.Dense, nn.LayerCount)
  282. // fmt.Printf("\nLoadState end\n")
  283. }
  284. func (nn *NeuralNetwork) forward(aIn mat.Matrix) {
  285. nn.A[0] = mat.DenseCopyOf(aIn)
  286. for l := 1; l < nn.LayerCount; l++ {
  287. nn.A[l] = mat.NewDense(nn.Sizes[l], 1, nil)
  288. aSrc := nn.A[l-1]
  289. aDst := nn.A[l]
  290. // Each iteration implements formula bellow for neuron activation values
  291. // A[l]=σ(W[l]*A[l−1]+B[l])
  292. // W[l]*A[l−1]
  293. aDst.Mul(nn.Weights[l], aSrc)
  294. // W[l]*A[l−1]+B[l]
  295. aDst.Add(aDst, nn.Biases[l])
  296. // Save raw activation value for back propagation
  297. nn.Z[l] = mat.DenseCopyOf(aDst)
  298. // σ(W[l]*A[l−1]+B[l])
  299. aDst.Apply(applySigmoid, aDst)
  300. }
  301. }
  302. // Function returns calculated bias and weights derivatives for each
  303. // layer arround aIn/aOut datasets
  304. func (nn *NeuralNetwork) backward(aIn, aOut mat.Matrix) (dB, dW []*mat.Dense) {
  305. nn.forward(aIn)
  306. lastLayerNum := nn.LayerCount - 1
  307. dB = make([]*mat.Dense, nn.LayerCount)
  308. dW = make([]*mat.Dense, nn.LayerCount)
  309. // To calculate new values of weights and biases
  310. // following formulas are used:
  311. // ∂E/∂W[l] = A[l−1]*δ[l]
  312. // ∂E/∂B[l] = δ[l]
  313. // For last layer δ value is calculated by following:
  314. // δ = (A[L]−y)⊙σ'(Z[L])
  315. // Calculate initial error for last layer L
  316. // error = A[L]-y
  317. // Where y is expected activations set
  318. err := &mat.Dense{}
  319. err.Sub(nn.result(), aOut)
  320. // Calculate sigmoids prime σ'(Z[L]) for last layer L
  321. sigmoidsPrime := &mat.Dense{}
  322. sigmoidsPrime.Apply(applySigmoidPrime, nn.Z[lastLayerNum])
  323. // (A[L]−y)⊙σ'(Z[L])
  324. delta := &mat.Dense{}
  325. delta.MulElem(err, sigmoidsPrime)
  326. // ∂E/∂B[L] = δ[L]
  327. biases := mat.DenseCopyOf(delta)
  328. // ∂E/∂W[L] = A[L−1]*δ[L]
  329. weights := &mat.Dense{}
  330. weights.Mul(delta, nn.A[lastLayerNum-1].T())
  331. // Initialize new weights and biases values with last layer values
  332. dB[lastLayerNum] = biases
  333. dW[lastLayerNum] = weights
  334. // Next layer derivatives of Weights and Biases are calculated using same formulas:
  335. // ∂E/∂W[l] = A[l−1]*δ[l]
  336. // ∂E/∂B[l] = δ[l]
  337. // But δ[l] is calculated using different formula:
  338. // δ[l] = ((Wt[l+1])*δ[l+1])⊙σ'(Z[l])
  339. // Where Wt[l+1] is transposed matrix of actual Weights from
  340. // forward step
  341. for l := nn.LayerCount - 2; l > 0; l-- {
  342. // Calculate sigmoids prime σ'(Z[l]) for last layer l
  343. sigmoidsPrime := &mat.Dense{}
  344. sigmoidsPrime.Apply(applySigmoidPrime, nn.Z[l])
  345. // (Wt[l+1])*δ[l+1]
  346. // err bellow is delta from previous step(l+1)
  347. wdelta := &mat.Dense{}
  348. wdelta.Mul(nn.Weights[l+1].T(), delta)
  349. // Calculate new delta and store it to temporary variable err
  350. // δ[l] = ((Wt[l+1])*δ[l+1])⊙σ'(Z[l])
  351. delta = &mat.Dense{}
  352. delta.MulElem(wdelta, sigmoidsPrime)
  353. // ∂E/∂B[l] = δ[l]
  354. biases := mat.DenseCopyOf(delta)
  355. // ∂E/∂W[l] = A[l−1]*δ[l]
  356. // At this point it's required to give explanation for inaccuracy
  357. // in the formula
  358. // Multiplying of activations matrix for layer l-1 and δ[l] is imposible
  359. // because view of matrices are following:
  360. // A[l-1] δ[l]
  361. // ⎡A[0] ⎤ ⎡δ[0] ⎤
  362. // ⎢A[1] ⎥ ⎢δ[1] ⎥
  363. // ⎢ ... ⎥ ⎢ ... ⎥
  364. // ⎢A[i] ⎥ X ⎢δ[i] ⎥
  365. // ⎢ ... ⎥ ⎢ ... ⎥
  366. // ⎣A[s'] ⎦ ⎣δ[s] ⎦
  367. // So we need to modify these matrices to apply mutiplications and got
  368. // Weights matrix of following view:
  369. // ⎡w[0,0] ... w[0,j] ... w[0,s']⎤
  370. // ⎢w[1,0] ... w[1,j] ... w[1,s']⎥
  371. // ⎢ ... ⎥
  372. // ⎢w[i,0] ... w[i,j] ... w[i,s']⎥
  373. // ⎢ ... ⎥
  374. // ⎣w[s,0] ... w[s,j] ... w[s,s']⎦
  375. // So we swap matrices and transpose A[l-1] to get valid multiplication
  376. // of following view:
  377. // δ[l] A[l-1]
  378. // ⎡δ[0] ⎤ x [A[0] A[1] ... A[i] ... A[s']]
  379. // ⎢δ[1] ⎥
  380. // ⎢ ... ⎥
  381. // ⎢δ[i] ⎥
  382. // ⎢ ... ⎥
  383. // ⎣δ[s] ⎦
  384. weights := &mat.Dense{}
  385. weights.Mul(delta, nn.A[l-1].T())
  386. dB[l] = biases
  387. dW[l] = weights
  388. }
  389. return
  390. }
  391. func (nn *NeuralNetwork) result() *mat.Dense {
  392. return nn.A[nn.LayerCount-1]
  393. }