neuralnetwork.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. /*
  2. * MIT License
  3. *
  4. * Copyright (c) 2019 Alexey Edelev <semlanik@gmail.com>
  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. "log"
  31. "os"
  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. //
  41. // Matrix: A
  42. // Description: A is set of calculated neuron activations after sigmoid correction
  43. // Format: 0 l L
  44. // ⎡A[0] ⎤ ... ⎡A[0] ⎤ ... ⎡A[0] ⎤
  45. // ⎢A[1] ⎥ ... ⎢A[1] ⎥ ... ⎢A[1] ⎥
  46. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  47. // ⎢A[i] ⎥ ... ⎢A[i] ⎥ ... ⎢A[i] ⎥
  48. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  49. // ⎣A[s] ⎦ ... ⎣A[s] ⎦ ... ⎣A[s] ⎦
  50. // Where s = Sizes[l] - Neural network layer size
  51. // L = len(Sizes) - Number of neural network layers
  52. //
  53. // Matrix: Z
  54. // Description: Z is set of calculated raw neuron activations
  55. // Format: 0 l L
  56. // ⎡Z[0] ⎤ ... ⎡Z[0] ⎤ ... ⎡Z[0] ⎤
  57. // ⎢Z[1] ⎥ ... ⎢Z[1] ⎥ ... ⎢Z[1] ⎥
  58. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  59. // ⎢Z[i] ⎥ ... ⎢Z[i] ⎥ ... ⎢Z[i] ⎥
  60. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  61. // ⎣Z[s] ⎦ ... ⎣Z[s] ⎦ ... ⎣Z[s] ⎦
  62. // Where s = Sizes[l] - Neural network layer size
  63. // L = len(Sizes) - Number of neural network layers
  64. //
  65. // Matrix: Biases
  66. // Description: Biases is set of biases per layer except l0
  67. // NOTE: l0 is always empty Dense because first layer
  68. // doesn't have connections to previous layer
  69. // Format: 1 l L
  70. // ⎡b[0] ⎤ ... ⎡b[0] ⎤ ... ⎡b[0] ⎤
  71. // ⎢b[1] ⎥ ... ⎢b[1] ⎥ ... ⎢b[1] ⎥
  72. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  73. // ⎢b[i] ⎥ ... ⎢b[i] ⎥ ... ⎢b[i] ⎥
  74. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  75. // ⎣b[s] ⎦ ... ⎣b[s] ⎦ ... ⎣b[s] ⎦
  76. // Where s = Sizes[l] - Neural network layer size
  77. // L = len(Sizes) - Number of neural network layers
  78. //
  79. // Matrix: Weights
  80. // Description: Weights is set of weights per layer except l0
  81. // NOTE: l0 is always empty Dense because first layer
  82. // doesn't have connections to previous layer
  83. // Format: 1 l L
  84. // ⎡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']⎤
  85. // ⎢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']⎥
  86. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  87. // ⎢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']⎥
  88. // ⎢ ... ⎥ ... ⎢ ... ⎥ ... ⎢ ... ⎥
  89. // ⎣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']⎦
  90. // Where s = Sizes[l] - Neural network layer size
  91. // s' = Sizes[l-1] - Previous neural network layer size
  92. // L = len(Sizes) - Number of neural network layers
  93. type NeuralNetwork struct {
  94. Count int
  95. Sizes []int
  96. Biases []*mat.Dense
  97. Weights []*mat.Dense
  98. A []*mat.Dense
  99. Z []*mat.Dense
  100. alpha float64
  101. trainingCycles int
  102. }
  103. func NewNeuralNetwork(sizes []int, nu float64, trainingCycles int) (nn *NeuralNetwork, err error) {
  104. err = nil
  105. if len(sizes) < 3 {
  106. fmt.Printf("Invalid network configuration: %v\n", sizes)
  107. return nil, errors.New("Invalid network configuration: %v\n")
  108. }
  109. for i := 0; i < len(sizes); i++ {
  110. if sizes[i] < 2 {
  111. fmt.Printf("Invalid network configuration: %v\n", sizes)
  112. return nil, errors.New("Invalid network configuration: %v\n")
  113. }
  114. }
  115. if nu <= 0.0 || nu > 1.0 {
  116. fmt.Printf("Invalid η value: %v\n", nu)
  117. return nil, errors.New("Invalid η value: %v\n")
  118. }
  119. if trainingCycles <= 0 {
  120. fmt.Printf("Invalid training cycles number: %v\n", trainingCycles)
  121. return nil, errors.New("Invalid training cycles number: %v\n")
  122. }
  123. if trainingCycles < 100 {
  124. fmt.Println("Training cycles number probably is too small")
  125. }
  126. nn = &NeuralNetwork{}
  127. nn.Sizes = sizes
  128. nn.Count = len(sizes)
  129. nn.Weights = make([]*mat.Dense, nn.Count)
  130. nn.Biases = make([]*mat.Dense, nn.Count)
  131. nn.A = make([]*mat.Dense, nn.Count)
  132. nn.Z = make([]*mat.Dense, nn.Count)
  133. nn.alpha = nu / float64(nn.Sizes[0])
  134. nn.trainingCycles = trainingCycles
  135. for i := 1; i < nn.Count; i++ {
  136. nn.Weights[i] = generateRandomDense(nn.Sizes[i], nn.Sizes[i-1])
  137. nn.Biases[i] = generateRandomDense(nn.Sizes[i], 1)
  138. }
  139. return
  140. }
  141. func (nn *NeuralNetwork) Copy() (out *NeuralNetwork) {
  142. out = &NeuralNetwork{}
  143. out.Sizes = nn.Sizes
  144. out.Count = nn.Count
  145. out.Weights = make([]*mat.Dense, nn.Count)
  146. out.Biases = make([]*mat.Dense, nn.Count)
  147. out.A = make([]*mat.Dense, nn.Count)
  148. out.Z = make([]*mat.Dense, nn.Count)
  149. out.alpha = nn.alpha
  150. out.trainingCycles = nn.trainingCycles
  151. for i := 1; i < out.Count; i++ {
  152. nn.Weights[i] = mat.DenseCopyOf(out.Weights[i])
  153. nn.Biases[i] = mat.DenseCopyOf(out.Biases[i])
  154. }
  155. return
  156. }
  157. func (nn *NeuralNetwork) Predict(aIn mat.Matrix) (maxIndex int, max float64) {
  158. r, _ := aIn.Dims()
  159. if r != nn.Sizes[0] {
  160. fmt.Printf("Invalid rows number of input matrix size: %v\n", r)
  161. return -1, 0.0
  162. }
  163. nn.forward(aIn)
  164. result := nn.result()
  165. r, _ = result.Dims()
  166. max = 0.0
  167. maxIndex = 0
  168. for i := 0; i < r; i++ {
  169. if result.At(i, 0) > max {
  170. max = result.At(i, 0)
  171. maxIndex = i
  172. }
  173. }
  174. return
  175. }
  176. func (nn *NeuralNetwork) Teach(teacher teach.Teacher) {
  177. for i := 0; i < nn.trainingCycles; i++ {
  178. for teacher.NextData() {
  179. nn.backward(teacher.GetData())
  180. }
  181. }
  182. }
  183. func check(e error) {
  184. if e != nil {
  185. panic(e)
  186. }
  187. }
  188. func (nn *NeuralNetwork) SaveState(filename string) {
  189. // Open file for reding
  190. inputFile, err := os.Create(filename)
  191. if err != nil {
  192. log.Fatal(err)
  193. }
  194. defer inputFile.Close()
  195. //save input array count
  196. bufferSize := make([]byte, 4)
  197. binary.LittleEndian.PutUint32(bufferSize[0:], uint32(nn.Count))
  198. n2, err := inputFile.Write(bufferSize)
  199. check(err)
  200. fmt.Printf("wrote value %d\n", uint32(nn.Count))
  201. // save an input array
  202. buffer := make([]byte, nn.Count*4)
  203. for i := 0; i < nn.Count; i++ {
  204. binary.LittleEndian.PutUint32(buffer[i*4:], uint32(nn.Sizes[i]))
  205. }
  206. n2, err = inputFile.Write(buffer)
  207. check(err)
  208. fmt.Printf("wrote buffer %d bytes\n", n2)
  209. //save biases
  210. ////////////////////////
  211. for i := 1; i < nn.Count; i++ {
  212. saveDense(inputFile, nn.Biases[i])
  213. }
  214. //save weights
  215. ////////////////////////
  216. for i := 1; i < nn.Count; i++ {
  217. saveDense(inputFile, nn.Weights[i])
  218. }
  219. }
  220. func saveDense(inputFile *os.File, matrix *mat.Dense) {
  221. buffer, _ := matrix.MarshalBinary()
  222. //save int size of Biases buffer
  223. bufferSize := make([]byte, 4)
  224. binary.LittleEndian.PutUint32(bufferSize, uint32(len(buffer)))
  225. inputFile.Write(bufferSize)
  226. bufferCount, err := inputFile.Write(buffer)
  227. check(err)
  228. fmt.Printf("wrote array size %d count of bytes %d \n", len(buffer), bufferCount)
  229. printMatDense(matrix)
  230. }
  231. func printMatDense(matrix *mat.Dense) {
  232. // Print the result using the formatter.
  233. fc := mat.Formatted(matrix, mat.Prefix(" "), mat.Squeeze())
  234. fmt.Printf("c = %v \n\n", fc)
  235. }
  236. func readDense(inputFile *os.File, matrix *mat.Dense) *mat.Dense {
  237. count := readInt(inputFile)
  238. fmt.Printf("%d \n\n", count)
  239. matrix = &mat.Dense{}
  240. matrix.UnmarshalBinary(readByteArray(inputFile, count))
  241. printMatDense(matrix)
  242. return matrix
  243. }
  244. func readByteArray(inputFile *os.File, size int) []byte {
  245. // Read an input array
  246. sizeBuffer := make([]byte, size)
  247. n1, err := inputFile.Read(sizeBuffer)
  248. check(err)
  249. fmt.Printf("readByteArray: size = %d \n", n1)
  250. return sizeBuffer
  251. }
  252. func readInt(inputFile *os.File) int {
  253. // Reade int
  254. count := make([]byte, 4)
  255. _, err := inputFile.Read(count)
  256. check(err)
  257. return int(binary.LittleEndian.Uint32(count))
  258. }
  259. func (nn *NeuralNetwork) LoadState(filename string) {
  260. inputFile, err := os.Open(filename)
  261. if err != nil {
  262. log.Fatal(err)
  263. }
  264. defer inputFile.Close()
  265. // Reade count
  266. nn.Count = readInt(inputFile)
  267. // Read an input array
  268. sizeBuffer := readByteArray(inputFile, nn.Count*4)
  269. nn.Sizes = make([]int, nn.Count)
  270. for i := 0; i < nn.Count; i++ {
  271. nn.Sizes[i] = int(binary.LittleEndian.Uint32(sizeBuffer[i*4:]))
  272. fmt.Printf("LoadState: nn.Sizes[%d] %d \n", i, nn.Sizes[i])
  273. }
  274. nn.Weights = []*mat.Dense{&mat.Dense{}}
  275. nn.Biases = []*mat.Dense{&mat.Dense{}}
  276. // read Biases
  277. nn.Biases[0] = &mat.Dense{}
  278. for i := 1; i < nn.Count; i++ {
  279. nn.Biases = append(nn.Biases, &mat.Dense{})
  280. nn.Biases[i] = readDense(inputFile, nn.Biases[i])
  281. }
  282. // read Weights
  283. nn.Weights[0] = &mat.Dense{}
  284. for i := 1; i < nn.Count; i++ {
  285. nn.Weights = append(nn.Weights, &mat.Dense{})
  286. nn.Weights[i] = readDense(inputFile, nn.Weights[i])
  287. }
  288. fmt.Printf("\nLoadState end\n")
  289. }
  290. func (nn *NeuralNetwork) forward(aIn mat.Matrix) {
  291. nn.A[0] = mat.DenseCopyOf(aIn)
  292. for i := 1; i < nn.Count; i++ {
  293. nn.A[i] = mat.NewDense(nn.Sizes[i], 1, nil)
  294. aSrc := nn.A[i-1]
  295. aDst := nn.A[i]
  296. // Each iteration implements formula bellow for neuron activation values
  297. // A[l]=σ(W[l]*A[l−1]+B[l])
  298. // W[l]*A[l−1]
  299. aDst.Mul(nn.Weights[i], aSrc)
  300. // W[l]*A[l−1]+B[l]
  301. aDst.Add(aDst, nn.Biases[i])
  302. // Save raw activation value for back propagation
  303. nn.Z[i] = mat.DenseCopyOf(aDst)
  304. // σ(W[l]*A[l−1]+B[l])
  305. aDst.Apply(applySigmoid, aDst)
  306. }
  307. }
  308. func (nn *NeuralNetwork) backward(aIn, aOut mat.Matrix) {
  309. nn.forward(aIn)
  310. lastLayerNum := nn.Count - 1
  311. // To calculate new values of weights and biases
  312. // following formulas are used:
  313. // W[l] = A[l−1]*δ[l]
  314. // B[l] = δ[l]
  315. // For last layer δ value is calculated by following:
  316. // δ = (A[L]−y)⊙σ'(Z[L])
  317. // Calculate initial error for last layer L
  318. // error = A[L]-y
  319. // Where y is expected activations set
  320. err := &mat.Dense{}
  321. err.Sub(nn.result(), aOut)
  322. // Calculate sigmoids prime σ'(Z[L]) for last layer L
  323. sigmoidsPrime := &mat.Dense{}
  324. sigmoidsPrime.Apply(applySigmoidPrime, nn.Z[lastLayerNum])
  325. // (A[L]−y)⊙σ'(Z[L])
  326. delta := &mat.Dense{}
  327. delta.MulElem(err, sigmoidsPrime)
  328. // B[L] = δ[L]
  329. biases := mat.DenseCopyOf(delta)
  330. // W[L] = A[L−1]*δ[L]
  331. weights := &mat.Dense{}
  332. weights.Mul(delta, nn.A[lastLayerNum-1].T())
  333. // Initialize new weights and biases values with last layer values
  334. newBiases := []*mat.Dense{makeBackGradient(biases, nn.Biases[lastLayerNum], nn.alpha)}
  335. newWeights := []*mat.Dense{makeBackGradient(weights, nn.Weights[lastLayerNum], nn.alpha)}
  336. // Save calculated delta value temporary error variable
  337. err = delta
  338. // Next layer Weights and Biases are calculated using same formulas:
  339. // W[l] = A[l−1]*δ[l]
  340. // B[l] = δ[l]
  341. // But δ[l] is calculated using different formula:
  342. // δ[l] = ((Wt[l+1])*δ[l+1])⊙σ'(Z[l])
  343. // Where Wt[l+1] is transposed matrix of actual Weights from
  344. // forward step
  345. for l := nn.Count - 2; l > 0; l-- {
  346. // Calculate sigmoids prime σ'(Z[l]) for last layer l
  347. sigmoidsPrime := &mat.Dense{}
  348. sigmoidsPrime.Apply(applySigmoidPrime, nn.Z[l])
  349. // (Wt[l+1])*δ[l+1]
  350. // err bellow is delta from previous step(l+1)
  351. delta := &mat.Dense{}
  352. wdelta := &mat.Dense{}
  353. wdelta.Mul(nn.Weights[l+1].T(), err)
  354. // Calculate new delta and store it to temporary variable err
  355. // δ[l] = ((Wt[l+1])*δ[l+1])⊙σ'(Z[l])
  356. delta.MulElem(wdelta, sigmoidsPrime)
  357. err = delta
  358. // B[l] = δ[l]
  359. biases := mat.DenseCopyOf(delta)
  360. // W[l] = A[l−1]*δ[l]
  361. // At this point it's required to give explanation for inaccuracy
  362. // in the formula
  363. // Multiplying of activations matrix for layer l-1 and δ[l] is imposible
  364. // because view of matrices are following:
  365. // A[l-1] δ[l]
  366. // ⎡A[0] ⎤ ⎡δ[0] ⎤
  367. // ⎢A[1] ⎥ ⎢δ[1] ⎥
  368. // ⎢ ... ⎥ ⎢ ... ⎥
  369. // ⎢A[i] ⎥ X ⎢δ[i] ⎥
  370. // ⎢ ... ⎥ ⎢ ... ⎥
  371. // ⎣A[s'] ⎦ ⎣δ[s] ⎦
  372. // So we need to modify these matrices to apply mutiplications and got
  373. // Weights matrix of following view:
  374. // ⎡w[0,0] ... w[0,j] ... w[0,s']⎤
  375. // ⎢w[1,0] ... w[1,j] ... w[1,s']⎥
  376. // ⎢ ... ⎥
  377. // ⎢w[i,0] ... w[i,j] ... w[i,s']⎥
  378. // ⎢ ... ⎥
  379. // ⎣w[s,0] ... w[s,j] ... w[s,s']⎦
  380. // So we swap matrices and transpose A[l-1] to get valid multiplication
  381. // of following view:
  382. // δ[l] A[l-1]
  383. // ⎡δ[0] ⎤ x [A[0] A[1] ... A[i] ... A[s']]
  384. // ⎢δ[1] ⎥
  385. // ⎢ ... ⎥
  386. // ⎢δ[i] ⎥
  387. // ⎢ ... ⎥
  388. // ⎣δ[s] ⎦
  389. weights := &mat.Dense{}
  390. weights.Mul(delta, nn.A[l-1].T())
  391. // !Prepend! new Biases and Weights
  392. newBiases = append([]*mat.Dense{makeBackGradient(biases, nn.Biases[l], nn.alpha)}, newBiases...)
  393. newWeights = append([]*mat.Dense{makeBackGradient(weights, nn.Weights[l], nn.alpha)}, newWeights...)
  394. }
  395. newBiases = append([]*mat.Dense{&mat.Dense{}}, newBiases...)
  396. newWeights = append([]*mat.Dense{&mat.Dense{}}, newWeights...)
  397. nn.Biases = newBiases
  398. nn.Weights = newWeights
  399. }
  400. func (nn *NeuralNetwork) result() *mat.Dense {
  401. return nn.A[nn.Count-1]
  402. }
  403. func (nn *NeuralNetwork) TeachResilient(aIn, aOut mat.Matrix, nuP, nuM float64, deltaMin, deltaMax float64) {
  404. }