c ++排序矢量快速配对作为遗传学习算法的一部分

问题描述 投票:-1回答:1

我有一个非常有趣的问题,我已经开始开发一种遗传学习算法,并且已经成功完成了这项工作。它是一个简单的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));
}

种群实体是矢量对,其中字符串和整数分别代表猜测和适应度。在调试代码之后,我发现群体确实包含正确的猜测但是具有错误的适应性,我认为排序算法比配对的字符串更快地移动整数。意味着在适应度函数期间,它选择一个项目作为一个字符不正确的答案,但是从另一个矢量实体移动了正确的适应性。

我已经尝试使用稳定排序并移动算法来查看时间是否有问题。但是,没有骰子。有没有办法让程序等待排序完成(这在时间上是低效的)或一种方法来使排序更快或实现更快的自定义排序算法,这将更有效,特别是在旧硬件上。

任何建议将不胜感激!

c++ algorithm artificial-intelligence
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.