genetic.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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 "../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. }
  52. // NewPopulation is constructor of new Population with specified PopulationVerifier, Mutagen and PopulationConfig.
  53. // sizes parameter also specified neuralnetwork.NeuralNetwork layers configuration
  54. func NewPopulation(verifier PopulationVerifier, mutagen Mutagen, populationConfig PopulationConfig, sizes []int) (p *Population) {
  55. if populationConfig.PopulationSize%2 != 0 {
  56. return nil
  57. }
  58. p = &Population{
  59. populationConfig: &populationConfig,
  60. Networks: make([]*neuralnetwork.NeuralNetwork, populationConfig.PopulationSize),
  61. verifier: verifier,
  62. mutagen: mutagen,
  63. etalonsCount: int(float64(populationConfig.PopulationSize) * populationConfig.SelectionSize),
  64. }
  65. if p.etalonsCount%2 != 0 {
  66. p.etalonsCount -= 1
  67. }
  68. for i := 0; i < populationConfig.PopulationSize; i++ {
  69. var err error
  70. p.Networks[i], err = neuralnetwork.NewNeuralNetwork(sizes, nil)
  71. if err != nil {
  72. log.Fatal("Could not initialize NeuralNetwork")
  73. }
  74. }
  75. return
  76. }
  77. // NaturalSelection invokes natural selection process for specified number of generation
  78. func (p *Population) NaturalSelection(generationCount int) {
  79. for g := 0; g < generationCount; g++ {
  80. p.crossbreedPopulation(p.verifier.Verify(p))
  81. }
  82. }
  83. func (p *Population) crossbreedPopulation(fitnesses []*IndividalFitness) {
  84. sort.Slice(fitnesses, func(i, j int) bool {
  85. return fitnesses[i].Fitness > fitnesses[j].Fitness //Descent order best will be on top, worst in the bottom
  86. })
  87. //Collect etalons from upper part of neural network list and crossbreed/mutate them
  88. etalonNetworks := make([]*neuralnetwork.NeuralNetwork, p.etalonsCount)
  89. for i := 1; i < p.etalonsCount; i += 2 {
  90. firstParent := fitnesses[i-1].Index
  91. secondParent := fitnesses[i].Index
  92. fmt.Printf("Result i %v firstParent %v secondParent %v firstFitness %v secondFitness %v\n", i, firstParent, secondParent, fitnesses[i-1].Fitness, fitnesses[i].Fitness)
  93. etalonNetworks[i-1] = p.Networks[firstParent].Copy()
  94. etalonNetworks[i] = p.Networks[secondParent].Copy()
  95. crossbreed(p.Networks[firstParent], p.Networks[secondParent], p.populationConfig.CrossbreedPart)
  96. p.mutagen.Mutate(p.Networks[firstParent])
  97. p.mutagen.Mutate(p.Networks[secondParent])
  98. }
  99. //Rest of networks are based on collected etalons but crossbreed/mutate own way
  100. for i := p.etalonsCount + 1; i < p.populationConfig.PopulationSize; i += 2 {
  101. firstParent := fitnesses[i-1].Index
  102. secondParent := fitnesses[i].Index
  103. fmt.Printf("Result i %v firstParent %v secondParent %v firstFitness %v secondFitness %v firstEtalon %v secondEtalon %v\n",
  104. i, firstParent, secondParent,
  105. fitnesses[i-1].Fitness, fitnesses[i].Fitness,
  106. fitnesses[(i-1)%p.etalonsCount].Index, fitnesses[(i)%p.etalonsCount].Index)
  107. firstParentEtalon := etalonNetworks[(i-1)%p.etalonsCount]
  108. secondParenEtalon := etalonNetworks[(i)%p.etalonsCount]
  109. p.Networks[firstParent] = firstParentEtalon.Copy()
  110. p.Networks[secondParent] = secondParenEtalon.Copy()
  111. crossbreed(p.Networks[firstParent], p.Networks[secondParent], p.populationConfig.CrossbreedPart)
  112. p.mutagen.Mutate(p.Networks[firstParent])
  113. p.mutagen.Mutate(p.Networks[secondParent])
  114. }
  115. }
  116. func crossbreed(firstParent, secondParent *neuralnetwork.NeuralNetwork, crossbreedPart float64) {
  117. for l := 1; l < firstParent.LayerCount; l++ {
  118. firstParentWeights := firstParent.Weights[l]
  119. secondParentWeights := secondParent.Weights[l]
  120. firstParentBiases := firstParent.Biases[l]
  121. secondParentBiases := secondParent.Biases[l]
  122. r, c := firstParentWeights.Dims()
  123. //Minimal part of matrix will be chosen for crossbreed
  124. rWindow := int(float64(r) * crossbreedPart)
  125. cWindow := int(float64(c) * crossbreedPart)
  126. r = int(rand.Uint32())%(r-rWindow) + rWindow
  127. c = int(rand.Uint32())%(c-cWindow) + cWindow
  128. for i := 0; i < r; i++ {
  129. for j := 0; j < c; j++ {
  130. // Swap weights
  131. w := firstParentWeights.At(i, j)
  132. firstParentWeights.Set(i, j, secondParentWeights.At(i, j))
  133. secondParentWeights.Set(i, j, w)
  134. }
  135. // Swap biases
  136. b := firstParentBiases.At(i, 0)
  137. firstParentBiases.Set(i, 0, secondParentBiases.At(i, 0))
  138. secondParentBiases.Set(i, 0, b)
  139. }
  140. }
  141. }