Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Ryokuchaneko/5999840 to your computer and use it in GitHub Desktop.
Save Ryokuchaneko/5999840 to your computer and use it in GitHub Desktop.
遺伝アルゴリズムを用いた最適化関数。ここでは旅程問題の最小コストの最適化を試みていますが、他の問題にも応用できます。かなり強力なアルゴリズムなのでオススメです。肌感としては、世代数を増やすよりも人口(ポピュレーション)を増やしたほうが良い解に辿り着ける可能性が高い気がします。
function geneticoptimize($domain, $origin, $people, $flights, $destination, $popsize = 50, $step=1, $mutprob=0.2, $elite=0.2, $maxiter = 100) {
function mutate($vec, $domain, $step) {
$i = rand(0, (count($domain) - 1));
$rand = rand(1,10000)/10000;
if(($rand < 0.5) && ($vec[$i] > $domain[$i][0])) {
$vec[$i] = $vec[$i] - $step;
return $vec;
} elseif($vec[$i] < $domain[$i][1]) {
$vec[$i] = $vec[$i] + $step;
return $vec;
}
}
function crossover($r1, $r2, $domain) {
$i = rand(1, (count($domain) - 2));
for($k = 0; $k < $i; $k++){
$r2[$k] = $r1[$k];
}
return $r2;
}
$pop = array();
for($y = 0; $y < $popsize; $y++){
$vec = array();
for($s = 0; $s < count($domain); $s++) {
$vec[] = rand($domain[$s][0], $domain[$s][1]);
}
$pop[] = $vec;
}
$topelite = floor($elite*$popsize);
for($g=0; $g<$maxiter; $g++){
$scores = array();
foreach($pop as $key => $v){
if(!empty($v)){
$scores[]=array(schedulecost($v, $origin, $people, $flights, $destination), $v);
}
}
sort($scores);
$pop = $ranked = array();
foreach($scores as $key => $v) {
$ranked[] = $v[1];
}
foreach($ranked as $v){
$pop[] = $v;
if(count($pop) == $topelite) {
break;
}
}
while(count($pop) <= $popsize) {
$randrand = rand(1,10000)/10000;
if($randrand < $mutprob){
$c = rand(0, $topelite);
$pop[] = mutate($ranked[$c], $domain, $step);
}else{
$c1 = rand(0, $topelite);
$c2 = rand(0, $topelite);
$pop[] = crossover($ranked[$c1], $ranked[$c2], $domain);
}
}
print $scores[0][0] . '<br />';
}
return $scores[0][1];
}
$result = geneticoptimize($domain, $origin, $people, $flights, $destination, $popsize = 50, $step=1, $mutprob=0.2, $elite=0.2, $maxiter = 100);
var_dump($result);
die();
$cost = schedulecost($result, $origin, $people, $flights, $destination);
var_dump($cost);
$schedule = printschedule($result, $people, $flights, $destination);
var_dump($schedule);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment