genetic.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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 genetic
  26. import (
  27. "fmt"
  28. "log"
  29. "math/rand"
  30. "sort"
  31. neuralnetwork "git.semlanik.org/semlanik/NeuralNetwork/neuralnetwork"
  32. )
  33. // Genetic package implements basic proncipals of genetic and natural selection mechanisms for
  34. // neuralnetwork.NeuralNetwork
  35. // PopulationConfig is structure that is used to specify population parameters
  36. // PopulationSize - size of population
  37. // SelectionSize - percentage of best individuals used for next generation
  38. // CrossbreedPart - percentage of weigts and biases used for crossbreed
  39. type PopulationConfig struct {
  40. PopulationSize int
  41. SelectionSize float64 // 0..1 percentage of success individuals to be used as parents for population
  42. CrossbreedPart float64 // 0..1 percentage of weights and biases to be exchanged beetween individuals while Crossbreed
  43. }
  44. // Population is main class for genetic and natural selection of neuralnetwork.NeuralNetwork
  45. type Population struct {
  46. populationConfig *PopulationConfig
  47. Networks []*neuralnetwork.NeuralNetwork
  48. verifier PopulationVerifier
  49. mutagen Mutagen
  50. etalonsCount int
  51. bestFitness *IndividalFitness
  52. bestNetwork *neuralnetwork.NeuralNetwork
  53. }
  54. // NewPopulation is constructor of new Population with specified PopulationVerifier, Mutagen and PopulationConfig.
  55. // sizes parameter also specified neuralnetwork.NeuralNetwork layers configuration
  56. func NewPopulation(verifier PopulationVerifier, mutagen Mutagen, populationConfig PopulationConfig, sizes []int) (p *Population) {
  57. if populationConfig.PopulationSize%2 != 0 {
  58. return nil
  59. }
  60. p = &Population{
  61. populationConfig: &populationConfig,
  62. Networks: make([]*neuralnetwork.NeuralNetwork, populationConfig.PopulationSize),
  63. verifier: verifier,
  64. mutagen: mutagen,
  65. etalonsCount: int(float64(populationConfig.PopulationSize) * populationConfig.SelectionSize),
  66. bestFitness: nil,
  67. bestNetwork: nil,
  68. }
  69. if p.etalonsCount%2 != 0 {
  70. p.etalonsCount -= 1
  71. }
  72. for i := 0; i < populationConfig.PopulationSize; i++ {
  73. var err error
  74. p.Networks[i], err = neuralnetwork.NewNeuralNetwork(sizes, nil)
  75. if err != nil {
  76. log.Fatal("Could not initialize NeuralNetwork")
  77. }
  78. }
  79. return
  80. }
  81. // NaturalSelection invokes natural selection process for specified number of generation
  82. func (p *Population) NaturalSelection(generationCount int) {
  83. for g := 0; g < generationCount; g++ {
  84. p.crossbreedPopulation(p.verifier.Verify(p))
  85. }
  86. }
  87. // GetBestNetwork method returns best network in population according to it fitness
  88. func (p *Population) GetBestNetwork() *neuralnetwork.NeuralNetwork {
  89. return p.bestNetwork
  90. }
  91. func (p *Population) crossbreedPopulation(fitnesses []*IndividalFitness) {
  92. sort.Slice(fitnesses, func(i, j int) bool {
  93. return fitnesses[i].Fitness > fitnesses[j].Fitness //Descent order best will be on top, worst in the bottom
  94. })
  95. //Save best fitness individal
  96. if p.bestFitness == nil || p.bestFitness.Fitness < fitnesses[0].Fitness {
  97. p.bestFitness = fitnesses[0]
  98. p.bestNetwork = p.Networks[fitnesses[0].Index].Copy()
  99. fmt.Printf("New best Fitness %v \n", fitnesses[0].Fitness)
  100. }
  101. //Collect etalons from upper part of neural network list and crossbreed/mutate them
  102. etalonNetworks := make([]*neuralnetwork.NeuralNetwork, p.etalonsCount)
  103. for i := 1; i < p.etalonsCount; i += 2 {
  104. firstParent := fitnesses[i-1].Index
  105. secondParent := fitnesses[i].Index
  106. fmt.Printf("Result i %v firstParent %v secondParent %v firstFitness %v secondFitness %v\n", i, firstParent, secondParent, fitnesses[i-1].Fitness, fitnesses[i].Fitness)
  107. etalonNetworks[i-1] = p.Networks[firstParent].Copy()
  108. etalonNetworks[i] = p.Networks[secondParent].Copy()
  109. crossbreed(p.Networks[firstParent], p.Networks[secondParent], p.populationConfig.CrossbreedPart)
  110. p.mutagen.Mutate(p.Networks[firstParent])
  111. p.mutagen.Mutate(p.Networks[secondParent])
  112. }
  113. //Rest of networks are based on collected etalons but crossbreed/mutate own way
  114. for i := p.etalonsCount + 1; i < p.populationConfig.PopulationSize; i += 2 {
  115. firstParent := fitnesses[i-1].Index
  116. secondParent := fitnesses[i].Index
  117. fmt.Printf("Result i %v firstParent %v secondParent %v firstFitness %v secondFitness %v firstEtalon %v secondEtalon %v\n",
  118. i, firstParent, secondParent,
  119. fitnesses[i-1].Fitness, fitnesses[i].Fitness,
  120. fitnesses[(i-1)%p.etalonsCount].Index, fitnesses[(i)%p.etalonsCount].Index)
  121. firstParentEtalon := etalonNetworks[(i-1)%p.etalonsCount]
  122. secondParenEtalon := etalonNetworks[(i)%p.etalonsCount]
  123. p.Networks[firstParent] = firstParentEtalon.Copy()
  124. p.Networks[secondParent] = secondParenEtalon.Copy()
  125. crossbreed(p.Networks[firstParent], p.Networks[secondParent], p.populationConfig.CrossbreedPart)
  126. p.mutagen.Mutate(p.Networks[firstParent])
  127. p.mutagen.Mutate(p.Networks[secondParent])
  128. }
  129. }
  130. func crossbreed(firstParent, secondParent *neuralnetwork.NeuralNetwork, crossbreedPart float64) {
  131. for l := 1; l < firstParent.LayerCount; l++ {
  132. firstParentWeights := firstParent.Weights[l]
  133. secondParentWeights := secondParent.Weights[l]
  134. firstParentBiases := firstParent.Biases[l]
  135. secondParentBiases := secondParent.Biases[l]
  136. r, c := firstParentWeights.Dims()
  137. //Minimal part of matrix will be chosen for crossbreed
  138. rWindow := int(float64(r) * crossbreedPart)
  139. cWindow := int(float64(c) * crossbreedPart)
  140. r = int(rand.Uint32())%(r-rWindow) + rWindow
  141. c = int(rand.Uint32())%(c-cWindow) + cWindow
  142. for i := 0; i < r; i++ {
  143. for j := 0; j < c; j++ {
  144. // Swap weights
  145. w := firstParentWeights.At(i, j)
  146. firstParentWeights.Set(i, j, secondParentWeights.At(i, j))
  147. secondParentWeights.Set(i, j, w)
  148. }
  149. // Swap biases
  150. b := firstParentBiases.At(i, 0)
  151. firstParentBiases.Set(i, 0, secondParentBiases.At(i, 0))
  152. secondParentBiases.Set(i, 0, b)
  153. }
  154. }
  155. }