neuralnetwork.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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. if watcher != nil {
  137. watcher.Init(nn)
  138. watcher.UpdateState(StateIdle)
  139. }
  140. }
  141. func (nn *NeuralNetwork) Predict(aIn mat.Matrix) (maxIndex int, max float64) {
  142. if nn.watcher != nil {
  143. nn.watcher.UpdateState(StatePredict)
  144. defer nn.watcher.UpdateState(StateIdle)
  145. }
  146. r, _ := aIn.Dims()
  147. if r != nn.Sizes[0] {
  148. fmt.Printf("Invalid rows number of input matrix size: %v\n", r)
  149. return -1, 0.0
  150. }
  151. A, _ := nn.forward(aIn)
  152. result := A[nn.layerCount-1]
  153. r, _ = result.Dims()
  154. max = 0.0
  155. maxIndex = 0
  156. for i := 0; i < r; i++ {
  157. if result.At(i, 0) > max {
  158. max = result.At(i, 0)
  159. maxIndex = i
  160. }
  161. }
  162. return
  163. }
  164. func (nn *NeuralNetwork) Teach(teacher teach.Teacher, epocs int) {
  165. if nn.watcher != nil {
  166. nn.watcher.UpdateState(StateLearning)
  167. defer nn.watcher.UpdateState(StateIdle)
  168. }
  169. if _, ok := nn.WGradient[nn.layerCount-1].(OnlineGradientDescent); ok {
  170. nn.TeachOnline(teacher, epocs)
  171. } else if _, ok := nn.WGradient[nn.layerCount-1].(BatchGradientDescent); ok {
  172. nn.TeachBatch(teacher, epocs)
  173. } else {
  174. panic("Invalid gradient descent type")
  175. }
  176. }
  177. func (nn *NeuralNetwork) TeachOnline(teacher teach.Teacher, epocs int) {
  178. for t := 0; t < epocs; t++ {
  179. for teacher.NextData() {
  180. dB, dW := nn.backward(teacher.GetData())
  181. for l := 1; l < nn.layerCount; l++ {
  182. bGradient, ok := nn.BGradient[l].(OnlineGradientDescent)
  183. if !ok {
  184. panic("bGradient is not a OnlineGradientDescent")
  185. }
  186. wGradient, ok := nn.WGradient[l].(OnlineGradientDescent)
  187. if !ok {
  188. panic("wGradient is not a OnlineGradientDescent")
  189. }
  190. nn.Biases[l] = bGradient.ApplyDelta(nn.Biases[l], dB[l])
  191. nn.Weights[l] = wGradient.ApplyDelta(nn.Weights[l], dW[l])
  192. if nn.watcher != nil {
  193. nn.watcher.UpdateBiases(l, nn.Biases[l])
  194. nn.watcher.UpdateWeights(l, nn.Weights[l])
  195. }
  196. }
  197. }
  198. teacher.Reset()
  199. }
  200. }
  201. func (nn *NeuralNetwork) TeachBatch(teacher teach.Teacher, epocs int) {
  202. for t := 0; t < epocs; t++ {
  203. batchWorkers := nn.runBatchWorkers(runtime.NumCPU(), teacher)
  204. for l := 1; l < nn.layerCount; l++ {
  205. bGradient, ok := nn.BGradient[l].(BatchGradientDescent)
  206. if !ok {
  207. panic("bGradient is not a BatchGradientDescent")
  208. }
  209. wGradient, ok := nn.WGradient[l].(BatchGradientDescent)
  210. if !ok {
  211. panic("wGradient is not a BatchGradientDescent")
  212. }
  213. for _, bw := range batchWorkers {
  214. dB, dW := bw.Result(l)
  215. bGradient.AccumGradients(dB)
  216. wGradient.AccumGradients(dW)
  217. }
  218. nn.Biases[l] = bGradient.ApplyDelta(nn.Biases[l])
  219. nn.Weights[l] = wGradient.ApplyDelta(nn.Weights[l])
  220. if nn.watcher != nil {
  221. nn.watcher.UpdateBiases(l, nn.Biases[l])
  222. nn.watcher.UpdateWeights(l, nn.Weights[l])
  223. }
  224. }
  225. //TODO: remove this is not used for visualization
  226. time.Sleep(100 * time.Millisecond)
  227. }
  228. }
  229. func (nn *NeuralNetwork) runBatchWorkers(threadCount int, teacher teach.Teacher) (workers []*batchWorker) {
  230. wg := sync.WaitGroup{}
  231. chunkSize := teacher.GetDataCount() / threadCount
  232. workers = make([]*batchWorker, threadCount)
  233. for i, _ := range workers {
  234. workers[i] = newBatchWorker(nn)
  235. wg.Add(1)
  236. s := i
  237. go func() {
  238. workers[s].Run(teacher, s*chunkSize, (s+1)*chunkSize)
  239. wg.Done()
  240. }()
  241. }
  242. wg.Wait()
  243. return
  244. }
  245. func (nn *NeuralNetwork) SaveState(writer io.Writer) {
  246. //save input array count
  247. bufferSize := make([]byte, 4)
  248. binary.LittleEndian.PutUint32(bufferSize[0:], uint32(nn.layerCount))
  249. _, err := writer.Write(bufferSize)
  250. check(err)
  251. fmt.Printf("wrote value %d\n", uint32(nn.layerCount))
  252. // save an input array
  253. buffer := make([]byte, nn.layerCount*4)
  254. for i := 0; i < nn.layerCount; i++ {
  255. binary.LittleEndian.PutUint32(buffer[i*4:], uint32(nn.Sizes[i]))
  256. }
  257. _, err = writer.Write(buffer)
  258. check(err)
  259. // fmt.Printf("wrote buffer %d bytes\n", n2)
  260. //save biases
  261. ////////////////////////
  262. for i := 1; i < nn.layerCount; i++ {
  263. saveDense(writer, nn.Biases[i])
  264. }
  265. //save weights
  266. ////////////////////////
  267. for i := 1; i < nn.layerCount; i++ {
  268. saveDense(writer, nn.Weights[i])
  269. }
  270. }
  271. func (nn *NeuralNetwork) LoadState(reader io.Reader) {
  272. // Reade count
  273. nn.layerCount = readInt(reader)
  274. // Read an input array
  275. sizeBuffer := readByteArray(reader, nn.layerCount*4)
  276. nn.Sizes = make([]int, nn.layerCount)
  277. for i := 0; i < nn.layerCount; i++ {
  278. nn.Sizes[i] = int(binary.LittleEndian.Uint32(sizeBuffer[i*4:]))
  279. // fmt.Printf("LoadState: nn.Sizes[%d] %d \n", i, nn.Sizes[i])
  280. }
  281. nn.Weights = []*mat.Dense{&mat.Dense{}}
  282. nn.Biases = []*mat.Dense{&mat.Dense{}}
  283. // read Biases
  284. nn.Biases[0] = &mat.Dense{}
  285. for i := 1; i < nn.layerCount; i++ {
  286. nn.Biases = append(nn.Biases, &mat.Dense{})
  287. nn.Biases[i] = readDense(reader, nn.Biases[i])
  288. }
  289. // read Weights
  290. nn.Weights[0] = &mat.Dense{}
  291. for i := 1; i < nn.layerCount; i++ {
  292. nn.Weights = append(nn.Weights, &mat.Dense{})
  293. nn.Weights[i] = readDense(reader, nn.Weights[i])
  294. }
  295. // fmt.Printf("\nLoadState end\n")
  296. }
  297. func (nn NeuralNetwork) forward(aIn mat.Matrix) (A, Z []*mat.Dense) {
  298. A = make([]*mat.Dense, nn.layerCount)
  299. Z = make([]*mat.Dense, nn.layerCount)
  300. A[0] = mat.DenseCopyOf(aIn)
  301. if nn.watcher != nil {
  302. nn.watcher.UpdateActivations(0, A[0])
  303. }
  304. for l := 1; l < nn.layerCount; l++ {
  305. A[l] = mat.NewDense(nn.Sizes[l], 1, nil)
  306. aSrc := A[l-1]
  307. aDst := A[l]
  308. // Each iteration implements formula bellow for neuron activation values
  309. // A[l]=σ(W[l]*A[l−1]+B[l])
  310. // W[l]*A[l−1]
  311. aDst.Mul(nn.Weights[l], aSrc)
  312. // W[l]*A[l−1]+B[l]
  313. aDst.Add(aDst, nn.Biases[l])
  314. // Save raw activation value for back propagation
  315. Z[l] = mat.DenseCopyOf(aDst)
  316. // σ(W[l]*A[l−1]+B[l])
  317. aDst.Apply(applySigmoid, aDst)
  318. if nn.watcher != nil {
  319. nn.watcher.UpdateActivations(l, aDst)
  320. }
  321. }
  322. return
  323. }
  324. // Function returns calculated bias and weights derivatives for each
  325. // layer arround aIn/aOut datasets
  326. func (nn NeuralNetwork) backward(aIn, aOut mat.Matrix) (dB, dW []*mat.Dense) {
  327. A, Z := nn.forward(aIn)
  328. lastLayerNum := nn.layerCount - 1
  329. dB = make([]*mat.Dense, nn.layerCount)
  330. dW = make([]*mat.Dense, nn.layerCount)
  331. // To calculate new values of weights and biases
  332. // following formulas are used:
  333. // ∂E/∂W[l] = A[l−1]*δ[l]
  334. // ∂E/∂B[l] = δ[l]
  335. // For last layer δ value is calculated by following:
  336. // δ = (A[L]−y)⊙σ'(Z[L])
  337. // Calculate initial error for last layer L
  338. // error = A[L]-y
  339. // Where y is expected activations set
  340. err := &mat.Dense{}
  341. err.Sub(A[nn.layerCount-1], aOut)
  342. // Calculate sigmoids prime σ'(Z[L]) for last layer L
  343. sigmoidsPrime := &mat.Dense{}
  344. sigmoidsPrime.Apply(applySigmoidPrime, Z[lastLayerNum])
  345. // (A[L]−y)⊙σ'(Z[L])
  346. delta := &mat.Dense{}
  347. delta.MulElem(err, sigmoidsPrime)
  348. // ∂E/∂B[L] = δ[L]
  349. biases := mat.DenseCopyOf(delta)
  350. // ∂E/∂W[L] = A[L−1]*δ[L]
  351. weights := &mat.Dense{}
  352. weights.Mul(delta, A[lastLayerNum-1].T())
  353. // Initialize new weights and biases values with last layer values
  354. dB[lastLayerNum] = biases
  355. dW[lastLayerNum] = weights
  356. // Next layer derivatives of Weights and Biases are calculated using same formulas:
  357. // ∂E/∂W[l] = A[l−1]*δ[l]
  358. // ∂E/∂B[l] = δ[l]
  359. // But δ[l] is calculated using different formula:
  360. // δ[l] = ((Wt[l+1])*δ[l+1])⊙σ'(Z[l])
  361. // Where Wt[l+1] is transposed matrix of actual Weights from
  362. // forward step
  363. for l := nn.layerCount - 2; l > 0; l-- {
  364. // Calculate sigmoids prime σ'(Z[l]) for last layer l
  365. sigmoidsPrime := &mat.Dense{}
  366. sigmoidsPrime.Apply(applySigmoidPrime, Z[l])
  367. // (Wt[l+1])*δ[l+1]
  368. // err bellow is delta from previous step(l+1)
  369. wdelta := &mat.Dense{}
  370. wdelta.Mul(nn.Weights[l+1].T(), delta)
  371. // Calculate new delta and store it to temporary variable err
  372. // δ[l] = ((Wt[l+1])*δ[l+1])⊙σ'(Z[l])
  373. delta = &mat.Dense{}
  374. delta.MulElem(wdelta, sigmoidsPrime)
  375. // ∂E/∂B[l] = δ[l]
  376. biases := mat.DenseCopyOf(delta)
  377. // ∂E/∂W[l] = A[l−1]*δ[l]
  378. // At this point it's required to give explanation for inaccuracy
  379. // in the formula
  380. // Multiplying of activations matrix for layer l-1 and δ[l] is imposible
  381. // because view of matrices are following:
  382. // A[l-1] δ[l]
  383. // ⎡A[0] ⎤ ⎡δ[0] ⎤
  384. // ⎢A[1] ⎥ ⎢δ[1] ⎥
  385. // ⎢ ... ⎥ ⎢ ... ⎥
  386. // ⎢A[i] ⎥ X ⎢δ[i] ⎥
  387. // ⎢ ... ⎥ ⎢ ... ⎥
  388. // ⎣A[s'] ⎦ ⎣δ[s] ⎦
  389. // So we need to modify these matrices to apply mutiplications and got
  390. // Weights matrix of following view:
  391. // ⎡w[0,0] ... w[0,j] ... w[0,s']⎤
  392. // ⎢w[1,0] ... w[1,j] ... w[1,s']⎥
  393. // ⎢ ... ⎥
  394. // ⎢w[i,0] ... w[i,j] ... w[i,s']⎥
  395. // ⎢ ... ⎥
  396. // ⎣w[s,0] ... w[s,j] ... w[s,s']⎦
  397. // So we swap matrices and transpose A[l-1] to get valid multiplication
  398. // of following view:
  399. // δ[l] A[l-1]
  400. // ⎡δ[0] ⎤ x [A[0] A[1] ... A[i] ... A[s']]
  401. // ⎢δ[1] ⎥
  402. // ⎢ ... ⎥
  403. // ⎢δ[i] ⎥
  404. // ⎢ ... ⎥
  405. // ⎣δ[s] ⎦
  406. weights := &mat.Dense{}
  407. weights.Mul(delta, A[l-1].T())
  408. dB[l] = biases
  409. dW[l] = weights
  410. }
  411. return
  412. }