作为遗传学习算法的一部分,快速将c ++分类向量对进行了

时间:2018-11-13 15:50:41

标签: c++ algorithm artificial-intelligence

我有一个非常有趣的问题,我已经开始开发基因学习算法,并成功地做到了。它是一种简单的GA,旨在通过随机选择要存储在字符串中的字符并使用标准的选择和变异方法进行搜索,直到找到最终答案为止,来找到一个短语,这有时效果很好。

但是,有时一个字符不正确。 我认为这是由于排序算法较慢。 这是我到目前为止所拥有的

这是循环代码

while (!word.Get_found())
{
    generation++;
    word.Calculate_fitness();
    word.Selection();   //selection
    word.Crossover();   //crossover

    system("cls");
    std::cout << "Generation: " << generation << " Highest fitness: " << word.get_fittest() << " with string: " << word.get_item() << "\n";
}

这是健身功能的代码

void Guess_word::Calculate_fitness()// calculates fittness based on guess 

word against matching string;
{
    for (int i = 0; i < population.size(); i++)
    {
        population.at(i).second = 0;
        for (int j = 0; j < population.at(i).first.size(); j++)
        {
            if (population.at(i).first.at(j) == Phrase.at(j))
            {
                population.at(i).second += 1;//calculate fitness
            }
        }
        if (population.at(i).second == Phrase.size() && population.at(i).first == Phrase)
        {
            found = true;
        }

    }

}

这是选择功能

void Guess_word::Selection()//determine highest fitness of population and make them parents
{
    //i hate stable sort....
    //it indicates to sort in pairs and keep them together
    std::sort(population.begin(), population.end(), [](auto &a, auto &b) { return a.second > b.second; });


    //select two random parent from mating pool
    parents.clear();

    parents.push_back(population.at(0));
    parents.push_back(population.at(1));
}

总体实体在矢量对中,带有分别代表猜测和适应度的字符串和整数。 调试代码后,我发现填充确实包含正确的猜测,但是适用性不正确,我认为排序算法将整数移动的速度比配对字符串快。表示在适应度函数中,它选择一个项目作为答案,该项目是一个字符不正确,但是正确的适应度已从另一个向量实体移出。

我尝试使用稳定的排序并移动算法以查看计时是否存在问题。但是,没有骰子。 有没有一种方法可以使程序等待排序完成(时间效率低下),或者可以使排序速度更快或实现更快的自定义排序算法,这将特别是在较旧的硬件上更加高效

任何建议将不胜感激!

1 个答案:

答案 0 :(得分:0)

问题很简单,代码进行交叉并将其存储回总体的位置0,使其在显示最终结果之前随机更改