neuralnetwork.go 14 KB

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