遗传算法的选择机制

时间:2016-05-15 11:08:20

标签: c++ genetic-algorithm mutation

我已经构建了一个遗传算法,但我觉得我的代码的选择/变异部分出了问题。这是我正在谈论的代码的一部分:

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <random>
#include <string>
#include <iomanip>
#include <math.h>

// The random number generator I am using.
std::random_device rd;
std::mt19937 rng(rd());

for (int k = 1; k < population_size; k++)                       // Loop until new population is filled up. K = 1 because first individual has the best genes from last generation.
{
// Calculate total fitness.

double totalfitness = 0;

for (int i = 0; i < population_size; i++)
{
    totalfitness += individuals[i].fitness;
}

// Calculate  relative fitness.

for (int i = 0; i < population_size; i++)
{
    individuals[i].probability = individuals[i].fitness / totalfitness;
}

std::uniform_real_distribution<double> dist2(0.0, 1.0);     // Initiate random number generator to generate a double between 0 and 1.

double rndNumber = dist2(rng);                              // Generate first double
double rndNumber2 = dist2(rng);                             // Generate second double
double offset = 0.0;                                        // Set offset (starting point from which it'll add up probabilities) at 0.
int father = 0;                                             // father is the individual that is picked, initialize at 0.
int mother = 0;

// Pick first parent. Once picked, set the fitness for that individual at 0 so that it can not be picked again.

for (int i = 0; i < population_size; i++)
{
    offset += individuals[i].probability;
    if (rndNumber < offset)
    {
        father = i;
        individuals[i].fitness = 0.0;
        break;
    }
}

offset = 0.0;       // Reset offset to zero because we'll start again for the second parent.
totalfitness = 0;   // Recalculate total fitness using only the remaining individuals and reset total fitness to 0

// Here we recalculate total fitness using only the fitness of the individuals remaining.

for (int i = 0; i < population_size; i++)
{
    totalfitness += individuals[i].fitness;
}

// Then we recalculate probability for the individuals based on the new totalfitness.

for (int i = 0; i < population_size; i++)
{
    individuals[i].probability = individuals[i].fitness / totalfitness;
}

// Then we give back the old fitness to the father/mother

individuals[father].fitness = 1 / (individuals[father].evaluation*individuals[father].evaluation);

// Then pick parent 2.

for (int i = 0; i < population_size; i++)
{
    offset += individuals[i].probability;
    if (rndNumber2 < offset)
    {
        mother = i;
        break;
    }
}

// Having picked father and mother, now the idea is to run a random number generator between 0 and 1 for each gene.
// So if:   father  {5, 8, 9, 3}
//          mother  {1, 5, 2, 6)
//          rndnum  {0, 0, 1, 1}
// then     child   {5, 8, 2, 6}

std::uniform_int_distribution<int> gene_selection(0, 1);        // Initiate random number generator to generate an integer between 0 and 1.

for (int i = 0; i < number_of_variables; i++)
{
    int gene1 = gene_selection(rng);
    if (gene1 == 0)
    {
        new_individuals[k].chromosomes[0].push_back(individuals[father].chromosomes[0].at(i));
    }
    else if (gene1 == 1)
    {
        new_individuals[k].chromosomes[0].push_back(individuals[mother].chromosomes[0].at(i));
    }
}

for (int j = 0; j < number_of_variables; j++)
{
    for (int l = 0; l < 32; l++)
    {
        std::uniform_int_distribution<int> mutation(0, 50);
        int mutation_outcome = mutation(rng);
        if (mutation_outcome == 1)
        {
            new_individuals[k].chromosomes[0].at(j) ^= (1 << l);
            if (new_individuals[k].chromosomes[0].at(j) == 0)
            {
                int new_var = uni(rng);
                new_individuals[k].chromosomes[0].at(j) = new_var;
            }
        }
    }
}
}

// When all new individuals have values, give individuals values of new_individuals and start next round of evaluation.

for (int i = 0; i < population_size; i++)
{
individuals[i] = new_individuals[i];
}

我的代码似乎工作正常。我似乎无法弄清楚它为何会逐渐恶化。它的前几代似乎经常找到新的,更好的解决方案。经过几代人的努力,它停止寻找新的最佳解决方案。

这当然可能是因为没有更好的解决方案,但我也同时在excel中进行计算,并且个人通常可以通过增加其中一条&#34;染色体来获得更好的适应性。 #34; 1,通常是1位变化,因为我通常用10000个人运行这个代码,你说这个程序必然会创建一个有这种变异的个体。

我现在已经使用调试器多次执行我的代码,在每一步显示值等等,但我似乎无法找出它出错的地方所以我想我会在这里发布我的代码,看看是否有人可以发现我搞砸了。

仅为记录,该算法只是一个公式求解器。所以我可以输入a = 1,b = 6,target = 50,a * gene1 + b * gene2,它(理论上)指定一个人越接近获得这个结果的适应度越高。< / p>

另外,如果我不得不猜测我搞砸了,我会在代码的变异部分说出来:

for (int j = 0; j < number_of_variables; j++)
{
    for (int l = 0; l < 32; l++)
    {
        std::uniform_int_distribution<int> mutation(0, 50);
        int mutation_outcome = mutation(rng);
        if (mutation_outcome == 1)
        {
            new_individuals[k].chromosomes[0].at(j) ^= (1 << l);
            if (new_individuals[k].chromosomes[0].at(j) == 0)
            {
                int new_var = uni(rng);
                new_individuals[k].chromosomes[0].at(j) = new_var;
            }
        }
    }
}

我这么说是因为这是我最不了解的部分,我可以想象我做了一个&#34;隐形&#34;错误。

无论如何,任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:0)

嗯,这只是让您的代码更好,更高效的一种方法。您正在使用std::uniform_int_distribution而没有播种,并且连续近5次呼叫,这可能是y our random number is not really random after all的原因。

一种简单的方法to get things betterseeding the random engine with time,从长远来看,可以授予更好的随机数创建(10000个人,不知何故大!)。

这里有link更好的解释,以及一个简单的代码片段如下:

#include <iostream>
#include <random> 

std::default_random_engine generator((unsigned int)time(0));
int random(int n) {
  std::uniform_int_distribution<int> distribution(0, n);
  return distribution(generator);
}
int main() {
        for(int i = 0; i < 15; ++i)
                std::cout << random(5) << " " << random(5)<< std::endl;
        return 0;
}
希望这会有所帮助!欢呼声,