neuralnetwork.go 15 KB

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