neuralnetwork.go 15 KB

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