neuralnetwork.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  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 neuralnetwork
  26. import (
  27. "encoding/binary"
  28. "errors"
  29. "fmt"
  30. "io"
  31. "os"
  32. "runtime"
  33. "sync"
  34. "time"
  35. training "git.semlanik.org/semlanik/NeuralNetwork/training"
  36. mat "gonum.org/v1/gonum/mat"
  37. )
  38. // NeuralNetwork is artificial neural network implementation
  39. //
  40. // Resources:
  41. // http://neuralnetworksanddeeplearning.com
  42. // https://www.youtube.com/watch?v=fNk_zzaMoSs
  43. // http://www.inf.fu-berlin.de/lehre/WS06/Musterererkennung/Paper/rprop.pdf
  44. //
  45. // Matrix: A (local matrices used in forward and backward methods)
  46. // Description: A is set of calculated neuron activations after sigmoid correction
  47. // Format: 0 l L
  48. // ⎡A[0] ⎤ ... ⎡A[0] ⎤ ... ⎡A[0] ⎤
  49. // ⎢A[1] ⎥ ... ⎢A[1] ⎥ ... ⎢A[1] ⎥
  50. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  51. // ⎢A[i] ⎥ ... ⎢A[i] ⎥ ... ⎢A[i] ⎥
  52. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  53. // ⎣A[s] ⎦ ... ⎣A[s] ⎦ ... ⎣A[s] ⎦
  54. // Where s = Sizes[l] - Neural network layer size
  55. // L = len(Sizes) - Number of neural network layers
  56. //
  57. // Matrix: Z (local matrices used in forward and backward methods)
  58. // Description: Z is set of calculated raw neuron activations
  59. // Format: 0 l L
  60. // ⎡Z[0] ⎤ ... ⎡Z[0] ⎤ ... ⎡Z[0] ⎤
  61. // ⎢Z[1] ⎥ ... ⎢Z[1] ⎥ ... ⎢Z[1] ⎥
  62. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  63. // ⎢Z[i] ⎥ ... ⎢Z[i] ⎥ ... ⎢Z[i] ⎥
  64. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  65. // ⎣Z[s] ⎦ ... ⎣Z[s] ⎦ ... ⎣Z[s] ⎦
  66. // Where s = Sizes[l] - Neural network layer size
  67. // L = len(Sizes) - Number of neural network layers
  68. //
  69. // Matrix: Biases
  70. // Description: Biases is set of biases per layer except l0
  71. // NOTE: l0 is always empty Dense because first layer
  72. // doesn't have connections to previous layer
  73. // Format: 1 l L
  74. // ⎡b[0] ⎤ ... ⎡b[0] ⎤ ... ⎡b[0] ⎤
  75. // ⎢b[1] ⎥ ... ⎢b[1] ⎥ ... ⎢b[1] ⎥
  76. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  77. // ⎢b[i] ⎥ ... ⎢b[i] ⎥ ... ⎢b[i] ⎥
  78. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  79. // ⎣b[s] ⎦ ... ⎣b[s] ⎦ ... ⎣b[s] ⎦
  80. // Where s = Sizes[l] - Neural network layer size
  81. // L = len(Sizes) - Number of neural network layers
  82. //
  83. // Matrix: Weights
  84. // Description: Weights is set of weights per layer except l0
  85. // NOTE: l0 is always empty Dense because first layer
  86. // doesn't have connections to previous layer
  87. // Format: 1 l L
  88. // ⎡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']⎤
  89. // ⎢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']⎥
  90. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  91. // ⎢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']⎥
  92. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  93. // ⎣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']⎦
  94. // Where s = Sizes[l] - Neural network layer size
  95. // s' = Sizes[l-1] - Previous neural network layer size
  96. // L = len(Sizes) - Number of neural network layers
  97. type NeuralNetwork struct {
  98. LayerCount int
  99. Sizes []int
  100. Biases []*mat.Dense
  101. Weights []*mat.Dense
  102. BGradient []interface{}
  103. WGradient []interface{}
  104. gradientDescentInitializer GradientDescentInitializer
  105. watcher StateWatcher
  106. syncMutex *sync.Mutex
  107. }
  108. // NewNeuralNetwork construction method that initializes new NeuralNetwork based
  109. // on provided list of layer sizes and GradientDescentInitializer that used for
  110. // backpropagation mechanism.
  111. // If gradientDescentInitializer is not provided (is nil) backpropagation won't
  112. // be possible. Common usecase when it's used is natural selection and genetic
  113. // training.
  114. func NewNeuralNetwork(sizes []int, gradientDescentInitializer GradientDescentInitializer) (nn *NeuralNetwork, err error) {
  115. err = nil
  116. if len(sizes) < 3 {
  117. fmt.Printf("Invalid network configuration: %v\n", sizes)
  118. return nil, errors.New("Invalid network configuration: %v\n")
  119. }
  120. for i := 0; i < len(sizes); i++ {
  121. if sizes[i] < 2 {
  122. fmt.Printf("Invalid network configuration: %v\n", sizes)
  123. return nil, errors.New("Invalid network configuration: %v\n")
  124. }
  125. }
  126. lenSizes := len(sizes)
  127. nn = &NeuralNetwork{
  128. Sizes: sizes,
  129. LayerCount: len(sizes),
  130. Biases: make([]*mat.Dense, lenSizes),
  131. Weights: make([]*mat.Dense, lenSizes),
  132. BGradient: make([]interface{}, lenSizes),
  133. WGradient: make([]interface{}, lenSizes),
  134. gradientDescentInitializer: gradientDescentInitializer,
  135. syncMutex: &sync.Mutex{},
  136. }
  137. for l := 1; l < nn.LayerCount; l++ {
  138. nn.Biases[l] = generateRandomDense(nn.Sizes[l], 1)
  139. nn.Weights[l] = generateRandomDense(nn.Sizes[l], nn.Sizes[l-1])
  140. if nn.gradientDescentInitializer != nil {
  141. nn.BGradient[l] = nn.gradientDescentInitializer(nn, l, BiasGradient)
  142. nn.WGradient[l] = nn.gradientDescentInitializer(nn, l, WeightGradient)
  143. }
  144. }
  145. return
  146. }
  147. // Copy makes complete copy of NeuralNetwork data. Output network has the same
  148. // weights and biases values and but might be used independend of original one,
  149. // e.g. in separate goroutine
  150. func (nn *NeuralNetwork) Copy() (outNN *NeuralNetwork) {
  151. nn.syncMutex.Lock()
  152. defer nn.syncMutex.Unlock()
  153. outNN = &NeuralNetwork{
  154. Sizes: nn.Sizes,
  155. LayerCount: len(nn.Sizes),
  156. Biases: make([]*mat.Dense, nn.LayerCount),
  157. Weights: make([]*mat.Dense, nn.LayerCount),
  158. BGradient: make([]interface{}, nn.LayerCount),
  159. WGradient: make([]interface{}, nn.LayerCount),
  160. gradientDescentInitializer: nn.gradientDescentInitializer,
  161. watcher: nn.watcher,
  162. syncMutex: &sync.Mutex{},
  163. }
  164. for l := 1; l < outNN.LayerCount; l++ {
  165. outNN.Biases[l] = mat.DenseCopyOf(nn.Biases[l])
  166. outNN.Weights[l] = mat.DenseCopyOf(nn.Weights[l])
  167. if outNN.gradientDescentInitializer != nil {
  168. outNN.BGradient[l] = outNN.gradientDescentInitializer(outNN, l, BiasGradient)
  169. outNN.WGradient[l] = outNN.gradientDescentInitializer(outNN, l, WeightGradient)
  170. }
  171. }
  172. return
  173. }
  174. // Reset resets network state to intial/random one with specified in argument
  175. // layers configuration
  176. func (nn *NeuralNetwork) Reset(sizes []int) (err error) {
  177. nn.syncMutex.Lock()
  178. defer nn.syncMutex.Unlock()
  179. err = nil
  180. if len(sizes) < 3 {
  181. fmt.Printf("Invalid network configuration: %v\n", sizes)
  182. return errors.New("Invalid network configuration: %v\n")
  183. }
  184. for i := 0; i < len(sizes); i++ {
  185. if sizes[i] < 2 {
  186. fmt.Printf("Invalid network configuration: %v\n", sizes)
  187. return errors.New("Invalid network configuration: %v\n")
  188. }
  189. }
  190. lenSizes := len(sizes)
  191. nn.Sizes = sizes
  192. nn.LayerCount = len(sizes)
  193. nn.Biases = make([]*mat.Dense, lenSizes)
  194. nn.Weights = make([]*mat.Dense, lenSizes)
  195. nn.BGradient = make([]interface{}, lenSizes)
  196. nn.WGradient = make([]interface{}, lenSizes)
  197. for l := 1; l < nn.LayerCount; l++ {
  198. nn.Biases[l] = generateRandomDense(nn.Sizes[l], 1)
  199. nn.Weights[l] = generateRandomDense(nn.Sizes[l], nn.Sizes[l-1])
  200. if nn.gradientDescentInitializer != nil {
  201. nn.BGradient[l] = nn.gradientDescentInitializer(nn, l, BiasGradient)
  202. nn.WGradient[l] = nn.gradientDescentInitializer(nn, l, WeightGradient)
  203. }
  204. }
  205. return
  206. }
  207. // SetStateWatcher setups state watcher for NeuralNetwork. StateWatcher is common
  208. // interface that collects data about NeuralNetwork behavior. If not specified (is
  209. // set to nil) NeuralNetwork will ignore StateWatcher interations
  210. func (nn *NeuralNetwork) SetStateWatcher(watcher StateWatcher) {
  211. nn.watcher = watcher
  212. if watcher != nil {
  213. watcher.Init(nn)
  214. if nn.watcher.GetSubscriptionFeatures().Has(StateSubscription) {
  215. watcher.UpdateState(StateIdle)
  216. }
  217. }
  218. }
  219. // Predict method invokes prediction based on input activations provided in argument.
  220. // Returns index of best element in output activation matrix and its value
  221. func (nn *NeuralNetwork) Predict(aIn mat.Matrix) (maxIndex int, max float64) {
  222. nn.syncMutex.Lock()
  223. defer nn.syncMutex.Unlock()
  224. if nn.watcher != nil {
  225. if nn.watcher.GetSubscriptionFeatures().Has(StateSubscription) {
  226. nn.watcher.UpdateState(StatePredict)
  227. defer nn.watcher.UpdateState(StateIdle)
  228. }
  229. }
  230. r, _ := aIn.Dims()
  231. if r != nn.Sizes[0] {
  232. fmt.Printf("Invalid rows number of input matrix size: %v\n", r)
  233. return -1, 0.0
  234. }
  235. A, _ := nn.forward(aIn)
  236. result := A[nn.LayerCount-1]
  237. r, _ = result.Dims()
  238. max = 0.0
  239. maxIndex = 0
  240. for i := 0; i < r; i++ {
  241. if result.At(i, 0) > max {
  242. max = result.At(i, 0)
  243. maxIndex = i
  244. }
  245. }
  246. return
  247. }
  248. // Validate runs basic network validation/verification based on validation data that
  249. // provided by training.Trainer passed as argument.
  250. // Returns count of failure predictions and total amount of verified samples.
  251. func (nn *NeuralNetwork) Validate(trainer training.Trainer) (failCount, total int) {
  252. nn.syncMutex.Lock()
  253. defer nn.syncMutex.Unlock()
  254. failCount = 0
  255. total = trainer.ValidatorCount()
  256. for i := 0; i < trainer.ValidatorCount(); i++ {
  257. dataSet, expect := trainer.GetValidator(i)
  258. index, _ := nn.Predict(dataSet)
  259. if expect.At(index, 0) != 1.0 {
  260. failCount++
  261. }
  262. }
  263. if nn.watcher != nil {
  264. if nn.watcher.GetSubscriptionFeatures().Has(ValidationSubscription) {
  265. nn.watcher.UpdateValidation(total, failCount)
  266. }
  267. }
  268. return
  269. }
  270. // Train is common training function that invokes one of training methods depends on
  271. // gradient descent used buy NeuralNetwork. training.Trainer passed as argument used
  272. // to get training data. Training loops are limited buy number of epocs
  273. func (nn *NeuralNetwork) Train(trainer training.Trainer, epocs int) {
  274. if nn.watcher != nil {
  275. if nn.watcher.GetSubscriptionFeatures().Has(StateSubscription) {
  276. nn.watcher.UpdateState(StateLearning)
  277. defer nn.watcher.UpdateState(StateIdle)
  278. }
  279. }
  280. if _, ok := nn.WGradient[nn.LayerCount-1].(OnlineGradientDescent); ok {
  281. nn.trainOnline(trainer, epocs)
  282. } else if _, ok := nn.WGradient[nn.LayerCount-1].(BatchGradientDescent); ok {
  283. nn.trainBatch(trainer, epocs)
  284. } else {
  285. panic("Invalid gradient descent type")
  286. }
  287. }
  288. func (nn *NeuralNetwork) trainOnline(trainer training.Trainer, epocs int) {
  289. for t := 0; t < epocs; t++ {
  290. for i := 0; i < trainer.DataCount(); i++ {
  291. if nn.watcher != nil {
  292. if nn.watcher.GetSubscriptionFeatures().Has(TrainingSubscription) {
  293. nn.watcher.UpdateTraining(t, epocs, i, trainer.DataCount())
  294. }
  295. }
  296. nn.syncMutex.Lock()
  297. dB, dW := nn.backward(trainer.GetData(i))
  298. for l := 1; l < nn.LayerCount; l++ {
  299. bGradient, ok := nn.BGradient[l].(OnlineGradientDescent)
  300. if !ok {
  301. panic("bGradient is not a OnlineGradientDescent")
  302. }
  303. wGradient, ok := nn.WGradient[l].(OnlineGradientDescent)
  304. if !ok {
  305. panic("wGradient is not a OnlineGradientDescent")
  306. }
  307. nn.Biases[l] = bGradient.ApplyDelta(nn.Biases[l], dB[l])
  308. nn.Weights[l] = wGradient.ApplyDelta(nn.Weights[l], dW[l])
  309. if nn.watcher != nil {
  310. if nn.watcher.GetSubscriptionFeatures().Has(BiasesSubscription) {
  311. nn.watcher.UpdateBiases(l, mat.DenseCopyOf(nn.Biases[l]))
  312. }
  313. if nn.watcher.GetSubscriptionFeatures().Has(WeightsSubscription) {
  314. nn.watcher.UpdateWeights(l, mat.DenseCopyOf(nn.Weights[l]))
  315. }
  316. }
  317. }
  318. nn.syncMutex.Unlock()
  319. }
  320. }
  321. }
  322. func (nn *NeuralNetwork) trainBatch(trainer training.Trainer, epocs int) {
  323. fmt.Printf("Start training in %v threads\n", runtime.NumCPU())
  324. for t := 0; t < epocs; t++ {
  325. if nn.watcher != nil {
  326. if nn.watcher.GetSubscriptionFeatures().Has(TrainingSubscription) {
  327. nn.watcher.UpdateTraining(t, epocs, 0, trainer.DataCount())
  328. }
  329. }
  330. batchWorkers := nn.runBatchWorkers(runtime.NumCPU(), trainer)
  331. nn.syncMutex.Lock()
  332. for l := 1; l < nn.LayerCount; l++ {
  333. bGradient, ok := nn.BGradient[l].(BatchGradientDescent)
  334. if !ok {
  335. panic("bGradient is not a BatchGradientDescent")
  336. }
  337. wGradient, ok := nn.WGradient[l].(BatchGradientDescent)
  338. if !ok {
  339. panic("wGradient is not a BatchGradientDescent")
  340. }
  341. for _, bw := range batchWorkers {
  342. dB, dW := bw.result(l)
  343. bGradient.AccumGradients(dB)
  344. wGradient.AccumGradients(dW)
  345. }
  346. nn.Biases[l] = bGradient.ApplyDelta(nn.Biases[l])
  347. nn.Weights[l] = wGradient.ApplyDelta(nn.Weights[l])
  348. if nn.watcher != nil {
  349. if nn.watcher.GetSubscriptionFeatures().Has(BiasesSubscription) {
  350. nn.watcher.UpdateBiases(l, mat.DenseCopyOf(nn.Biases[l]))
  351. }
  352. if nn.watcher.GetSubscriptionFeatures().Has(WeightsSubscription) {
  353. nn.watcher.UpdateWeights(l, mat.DenseCopyOf(nn.Weights[l]))
  354. }
  355. }
  356. }
  357. nn.syncMutex.Unlock()
  358. //TODO: remove this is not used for visualization
  359. time.Sleep(100 * time.Millisecond)
  360. }
  361. }
  362. func (nn *NeuralNetwork) runBatchWorkers(threadCount int, trainer training.Trainer) (workers []*batchWorker) {
  363. wg := sync.WaitGroup{}
  364. chunkSize := trainer.DataCount() / threadCount
  365. workers = make([]*batchWorker, threadCount)
  366. for i, _ := range workers {
  367. workers[i] = newBatchWorker(nn)
  368. wg.Add(1)
  369. s := i
  370. go func() {
  371. workers[s].run(trainer, s*chunkSize, (s+1)*chunkSize)
  372. wg.Done()
  373. }()
  374. }
  375. wg.Wait()
  376. return
  377. }
  378. // SaveState saves state of NeuralNetwork to io.Writer. It's usefull to keep training results
  379. // between NeuralNetwork "power cycles" or to share traing results between clustered neural
  380. // network hosts
  381. func (nn *NeuralNetwork) SaveState(writer io.Writer) {
  382. nn.syncMutex.Lock()
  383. defer nn.syncMutex.Unlock()
  384. //save input array count
  385. bufferSize := make([]byte, 4)
  386. binary.LittleEndian.PutUint32(bufferSize[0:], uint32(nn.LayerCount))
  387. _, err := writer.Write(bufferSize)
  388. check(err)
  389. //fmt.Printf("wrote value %d\n", uint32(nn.LayerCount))
  390. // save an input array
  391. buffer := make([]byte, nn.LayerCount*4)
  392. for i := 0; i < nn.LayerCount; i++ {
  393. binary.LittleEndian.PutUint32(buffer[i*4:], uint32(nn.Sizes[i]))
  394. }
  395. _, err = writer.Write(buffer)
  396. check(err)
  397. // fmt.Printf("wrote buffer %d bytes\n", n2)
  398. //save biases
  399. for i := 1; i < nn.LayerCount; i++ {
  400. saveDense(writer, nn.Biases[i])
  401. }
  402. //save weights
  403. for i := 1; i < nn.LayerCount; i++ {
  404. saveDense(writer, nn.Weights[i])
  405. }
  406. }
  407. // SaveStateToFile saves NeuralNetwork state to file by specific filePath
  408. func (nn *NeuralNetwork) SaveStateToFile(filePath string) {
  409. outFile, err := os.OpenFile(filePath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
  410. check(err)
  411. defer outFile.Close()
  412. nn.SaveState(outFile)
  413. }
  414. // LoadState loads NeuralNetwork state from io.Reader. All existing data in NeuralNetwork
  415. // will be rewritten buy this method, including layers configuration and weights and biases
  416. func (nn *NeuralNetwork) LoadState(reader io.Reader) {
  417. nn.syncMutex.Lock()
  418. defer nn.syncMutex.Unlock()
  419. // Reade count
  420. nn.LayerCount = readInt(reader)
  421. // Read an input array
  422. sizeBuffer := readByteArray(reader, nn.LayerCount*4)
  423. nn.Sizes = make([]int, nn.LayerCount)
  424. for l := 0; l < nn.LayerCount; l++ {
  425. nn.Sizes[l] = int(binary.LittleEndian.Uint32(sizeBuffer[l*4:]))
  426. fmt.Printf("LoadState: nn.Sizes[%d] %d \n", l, nn.Sizes[l])
  427. }
  428. nn.Weights = []*mat.Dense{&mat.Dense{}}
  429. nn.Biases = []*mat.Dense{&mat.Dense{}}
  430. // read Biases
  431. nn.Biases[0] = &mat.Dense{}
  432. for l := 1; l < nn.LayerCount; l++ {
  433. nn.Biases = append(nn.Biases, &mat.Dense{})
  434. nn.Biases[l] = readDense(reader, nn.Biases[l])
  435. }
  436. // read Weights and initialize gradient descents
  437. nn.BGradient = make([]interface{}, nn.LayerCount)
  438. nn.WGradient = make([]interface{}, nn.LayerCount)
  439. nn.Weights[0] = &mat.Dense{}
  440. for l := 1; l < nn.LayerCount; l++ {
  441. nn.Weights = append(nn.Weights, &mat.Dense{})
  442. nn.Weights[l] = readDense(reader, nn.Weights[l])
  443. if nn.gradientDescentInitializer != nil {
  444. nn.BGradient[l] = nn.gradientDescentInitializer(nn, l, BiasGradient)
  445. nn.WGradient[l] = nn.gradientDescentInitializer(nn, l, WeightGradient)
  446. }
  447. }
  448. // fmt.Printf("\nLoadState end\n")
  449. }
  450. // LoadStateFromFile loads NeuralNetwork state from file by specific filePath
  451. func (nn *NeuralNetwork) LoadStateFromFile(filePath string) {
  452. inFile, err := os.Open(filePath)
  453. check(err)
  454. defer inFile.Close()
  455. nn.LoadState(inFile)
  456. }
  457. func (nn NeuralNetwork) forward(aIn mat.Matrix) (A, Z []*mat.Dense) {
  458. A = make([]*mat.Dense, nn.LayerCount)
  459. Z = make([]*mat.Dense, nn.LayerCount)
  460. A[0] = mat.DenseCopyOf(aIn)
  461. if nn.watcher != nil {
  462. if nn.watcher.GetSubscriptionFeatures().Has(ActivationsSubscription) {
  463. nn.watcher.UpdateActivations(0, mat.DenseCopyOf(A[0]))
  464. }
  465. }
  466. for l := 1; l < nn.LayerCount; l++ {
  467. A[l] = mat.NewDense(nn.Sizes[l], 1, nil)
  468. aSrc := A[l-1]
  469. aDst := A[l]
  470. // Each iteration implements formula bellow for neuron activation values
  471. // A[l]=σ(W[l]*A[l−1]+B[l])
  472. // W[l]*A[l−1]
  473. aDst.Mul(nn.Weights[l], aSrc)
  474. // W[l]*A[l−1]+B[l]
  475. aDst.Add(aDst, nn.Biases[l])
  476. // Save raw activation value for back propagation
  477. Z[l] = mat.DenseCopyOf(aDst)
  478. // σ(W[l]*A[l−1]+B[l])
  479. aDst.Apply(applySigmoid, aDst)
  480. if nn.watcher != nil {
  481. if nn.watcher.GetSubscriptionFeatures().Has(ActivationsSubscription) {
  482. nn.watcher.UpdateActivations(l, mat.DenseCopyOf(aDst))
  483. }
  484. }
  485. }
  486. return
  487. }
  488. // Function returns calculated bias and weights derivatives for each
  489. // layer arround aIn/aOut datasets
  490. func (nn NeuralNetwork) backward(aIn, aOut mat.Matrix) (dB, dW []*mat.Dense) {
  491. A, Z := nn.forward(aIn)
  492. lastLayerNum := nn.LayerCount - 1
  493. dB = make([]*mat.Dense, nn.LayerCount)
  494. dW = make([]*mat.Dense, nn.LayerCount)
  495. // To calculate new values of weights and biases
  496. // following formulas are used:
  497. // ∂E/∂W[l] = A[l−1]*δ[l]
  498. // ∂E/∂B[l] = δ[l]
  499. // For last layer δ value is calculated by following:
  500. // δ = (A[L]−y)⊙σ'(Z[L])
  501. // Calculate initial error for last layer L
  502. // error = A[L]-y
  503. // Where y is expected activations set
  504. err := &mat.Dense{}
  505. err.Sub(A[nn.LayerCount-1], aOut)
  506. // Calculate sigmoids prime σ'(Z[L]) for last layer L
  507. sigmoidsPrime := &mat.Dense{}
  508. sigmoidsPrime.Apply(applySigmoidPrime, Z[lastLayerNum])
  509. // (A[L]−y)⊙σ'(Z[L])
  510. delta := &mat.Dense{}
  511. delta.MulElem(err, sigmoidsPrime)
  512. // ∂E/∂B[L] = δ[L]
  513. biases := mat.DenseCopyOf(delta)
  514. // ∂E/∂W[L] = A[L−1]*δ[L]
  515. weights := &mat.Dense{}
  516. weights.Mul(delta, A[lastLayerNum-1].T())
  517. // Initialize new weights and biases values with last layer values
  518. dB[lastLayerNum] = biases
  519. dW[lastLayerNum] = weights
  520. // Next layer derivatives of Weights and Biases are calculated using same formulas:
  521. // ∂E/∂W[l] = A[l−1]*δ[l]
  522. // ∂E/∂B[l] = δ[l]
  523. // But δ[l] is calculated using different formula:
  524. // δ[l] = ((Wt[l+1])*δ[l+1])⊙σ'(Z[l])
  525. // Where Wt[l+1] is transposed matrix of actual Weights from
  526. // forward step
  527. for l := nn.LayerCount - 2; l > 0; l-- {
  528. // Calculate sigmoids prime σ'(Z[l]) for last layer l
  529. sigmoidsPrime := &mat.Dense{}
  530. sigmoidsPrime.Apply(applySigmoidPrime, Z[l])
  531. // (Wt[l+1])*δ[l+1]
  532. // err bellow is delta from previous step(l+1)
  533. wdelta := &mat.Dense{}
  534. wdelta.Mul(nn.Weights[l+1].T(), delta)
  535. // Calculate new delta and store it to temporary variable err
  536. // δ[l] = ((Wt[l+1])*δ[l+1])⊙σ'(Z[l])
  537. delta = &mat.Dense{}
  538. delta.MulElem(wdelta, sigmoidsPrime)
  539. // ∂E/∂B[l] = δ[l]
  540. biases := mat.DenseCopyOf(delta)
  541. // ∂E/∂W[l] = A[l−1]*δ[l]
  542. // At this point it's required to give explanation for inaccuracy
  543. // in the formula
  544. // Multiplying of activations matrix for layer l-1 and δ[l] is imposible
  545. // because view of matrices are following:
  546. // A[l-1] δ[l]
  547. // ⎡A[0] ⎤ ⎡δ[0] ⎤
  548. // ⎢A[1] ⎥ ⎢δ[1] ⎥
  549. // ⎢ ... ⎥ ⎢ ... ⎥
  550. // ⎢A[i] ⎥ X ⎢δ[i] ⎥
  551. // ⎢ ... ⎥ ⎢ ... ⎥
  552. // ⎣A[s'] ⎦ ⎣δ[s] ⎦
  553. // So we need to modify these matrices to apply mutiplications and got
  554. // Weights matrix of following view:
  555. // ⎡w[0,0] ... w[0,j] ... w[0,s']⎤
  556. // ⎢w[1,0] ... w[1,j] ... w[1,s']⎥
  557. // ⎢ ... ⎥
  558. // ⎢w[i,0] ... w[i,j] ... w[i,s']⎥
  559. // ⎢ ... ⎥
  560. // ⎣w[s,0] ... w[s,j] ... w[s,s']⎦
  561. // So we swap matrices and transpose A[l-1] to get valid multiplication
  562. // of following view:
  563. // δ[l] A[l-1]
  564. // ⎡δ[0] ⎤ x [A[0] A[1] ... A[i] ... A[s']]
  565. // ⎢δ[1] ⎥
  566. // ⎢ ... ⎥
  567. // ⎢δ[i] ⎥
  568. // ⎢ ... ⎥
  569. // ⎣δ[s] ⎦
  570. weights := &mat.Dense{}
  571. weights.Mul(delta, A[l-1].T())
  572. dB[l] = biases
  573. dW[l] = weights
  574. }
  575. return
  576. }