genetic.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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. type PopulationConfig struct {
  34. PopulationSize int
  35. SelectionSize float64 // 0..1 persentage of success individuals to be used as parents for population
  36. CrossbreedPart float64 // 0..1 persentage of weights and biases to be exchanged beetween individuals while Crossbreed
  37. }
  38. type Population struct {
  39. populationConfig *PopulationConfig
  40. Networks []*neuralnetwork.NeuralNetwork
  41. verifier PopulationVerifier
  42. mutagen Mutagen
  43. etalonsCount int
  44. }
  45. func NewPopulation(verifier PopulationVerifier, mutagen Mutagen, populationConfig PopulationConfig, sizes []int) (p *Population) {
  46. if populationConfig.PopulationSize%2 != 0 {
  47. return nil
  48. }
  49. p = &Population{
  50. populationConfig: &populationConfig,
  51. Networks: make([]*neuralnetwork.NeuralNetwork, populationConfig.PopulationSize),
  52. verifier: verifier,
  53. mutagen: mutagen,
  54. etalonsCount: int(float64(populationConfig.PopulationSize) * populationConfig.SelectionSize),
  55. }
  56. if p.etalonsCount%2 != 0 {
  57. p.etalonsCount -= 1
  58. }
  59. for i := 0; i < populationConfig.PopulationSize; i++ {
  60. var err error
  61. p.Networks[i], err = neuralnetwork.NewNeuralNetwork(sizes, nil)
  62. if err != nil {
  63. log.Fatal("Could not initialize NeuralNetwork")
  64. }
  65. }
  66. return
  67. }
  68. func (p *Population) NaturalSelection(generationCount int) {
  69. for g := 0; g < generationCount; g++ {
  70. p.crossbreedPopulation(p.verifier.Verify(p))
  71. }
  72. }
  73. func (p *Population) crossbreedPopulation(fitnesses []*IndividalFitness) {
  74. sort.Slice(fitnesses, func(i, j int) bool {
  75. return fitnesses[i].Fitness > fitnesses[j].Fitness //Descent order best will be on top, worst in the bottom
  76. })
  77. //Collect etalons from upper part of neural network list and crossbreed/mutate them
  78. etalonNetworks := make([]*neuralnetwork.NeuralNetwork, p.etalonsCount)
  79. for i := 1; i < p.etalonsCount; i += 2 {
  80. firstParent := fitnesses[i-1].Index
  81. secondParent := fitnesses[i].Index
  82. fmt.Printf("Result i %v firstParent %v secondParent %v firstFitness %v secondFitness %v\n", i, firstParent, secondParent, fitnesses[i-1].Fitness, fitnesses[i].Fitness)
  83. etalonNetworks[i-1] = p.Networks[firstParent].Copy()
  84. etalonNetworks[i] = p.Networks[secondParent].Copy()
  85. crossbreed(p.Networks[firstParent], p.Networks[secondParent], p.populationConfig.CrossbreedPart)
  86. p.mutagen.Mutate(p.Networks[firstParent])
  87. p.mutagen.Mutate(p.Networks[secondParent])
  88. }
  89. //Rest of networks are based on collected etalons but crossbreed/mutate own way
  90. for i := p.etalonsCount + 1; i < p.populationConfig.PopulationSize; i += 2 {
  91. firstParent := fitnesses[i-1].Index
  92. secondParent := fitnesses[i].Index
  93. fmt.Printf("Result i %v firstParent %v secondParent %v firstFitness %v secondFitness %v firstEtalon %v secondEtalon %v\n",
  94. i, firstParent, secondParent,
  95. fitnesses[i-1].Fitness, fitnesses[i].Fitness,
  96. fitnesses[(i-1)%p.etalonsCount].Index, fitnesses[(i)%p.etalonsCount].Index)
  97. firstParentEtalon := etalonNetworks[(i-1)%p.etalonsCount]
  98. secondParenEtalon := etalonNetworks[(i)%p.etalonsCount]
  99. p.Networks[firstParent] = firstParentEtalon.Copy()
  100. p.Networks[secondParent] = secondParenEtalon.Copy()
  101. crossbreed(p.Networks[firstParent], p.Networks[secondParent], p.populationConfig.CrossbreedPart)
  102. p.mutagen.Mutate(p.Networks[firstParent])
  103. p.mutagen.Mutate(p.Networks[secondParent])
  104. }
  105. }
  106. func crossbreed(firstParent, secondParent *neuralnetwork.NeuralNetwork, crossbreedPart float64) {
  107. for l := 1; l < firstParent.LayerCount; l++ {
  108. firstParentWeights := firstParent.Weights[l]
  109. secondParentWeights := secondParent.Weights[l]
  110. firstParentBiases := firstParent.Biases[l]
  111. secondParentBiases := secondParent.Biases[l]
  112. r, c := firstParentWeights.Dims()
  113. //Minimal part of matrix will be chosen for crossbreed
  114. rWindow := int(float64(r) * crossbreedPart)
  115. cWindow := int(float64(c) * crossbreedPart)
  116. r = int(rand.Uint32())%(r-rWindow) + rWindow
  117. c = int(rand.Uint32())%(c-cWindow) + cWindow
  118. for i := 0; i < r; i++ {
  119. for j := 0; j < c; j++ {
  120. // Swap weights
  121. w := firstParentWeights.At(i, j)
  122. firstParentWeights.Set(i, j, secondParentWeights.At(i, j))
  123. secondParentWeights.Set(i, j, w)
  124. }
  125. // Swap biases
  126. b := firstParentBiases.At(i, 0)
  127. firstParentBiases.Set(i, 0, secondParentBiases.At(i, 0))
  128. secondParentBiases.Set(i, 0, b)
  129. }
  130. }
  131. }