forked from Wei-1/Scala-Machine-Learning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGeneAlgorithm.scala
41 lines (36 loc) · 1.32 KB
/
GeneAlgorithm.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Wei Chen - Gene algorithm
// 2017-07-22
package com.scalaml.algorithm
class GeneAlgorithm {
var seeds: Array[Array[Double]] = null
def setSeeds(newseeds: Array[Array[Double]]): Unit = seeds = newseeds
def evolve(
evaluation: Array[Double] => Double,
breeding: (Array[Double], Array[Double]) => Array[Array[Double]],
generationsize: Int = 100,
elitesize: Int = 3
): Array[Double] = {
val parents = seeds.sortBy { arr =>
evaluation(arr)
}.takeRight(elitesize)
val parentsize = parents.size
val kids = (0 until generationsize - parentsize).flatMap { i =>
val ai = scala.util.Random.nextInt.abs % parentsize
val bi = scala.util.Random.nextInt.abs % parentsize
breeding(parents(ai), parents(bi))
}
seeds = parents ++ kids
parents.last // return the best
}
def search(
evaluation: Array[Double] => Double,
breeding: (Array[Double], Array[Double]) => Array[Array[Double]],
generationsize: Int = 100,
elitesize: Int = 3,
generationcount: Int = 10
): Array[Double] = {
for (i <- 1 until generationcount)
evolve(evaluation, breeding, generationsize, elitesize)
evolve(evaluation, breeding, generationsize, elitesize)
}
}