加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

我无法使用python中的遗传算法得到正确的答案

发布时间:2020-05-24 22:32:23 所属栏目:Python 来源:互联网
导读:我试图用python写一个简单的生成算法,应该给我提供“ Hello World”.它工作正常,但无法通过“最大迭代”常量给出核心答案.它只是在无限循环中工作.这是我的代码如下:import random class GAHello(): POPULATION_SIZE = 1000 ELITE_RATE = 0.1 SURVIVE

我试图用python写一个简单的生成算法,应该给我提供“ Hello World”.它工作正常,但无法通过“最大迭代”常量给出核心答案.它只是在无限循环中工作.

这是我的代码如下:

import random

class GAHello():
    POPULATION_SIZE = 1000
    ELITE_RATE = 0.1
    SURVIVE_RATE = 0.5
    MUTATION_RATE = 0.2
    TARGET = "Hello World!"
    MAX_ITER = 1000

    def InitializePopulation(self):
        tsize: int = len(self.TARGET)
        population = list()

        for i in range(0,self.POPULATION_SIZE):
            str = ''
            for j in range(0,tsize):
                str += chr(int(random.random() * 255))

            citizen: Genome = Genome(str)
            population.append(citizen)
        return population

    def Mutation(self,strng):
        tsize: int = len(self.TARGET)
        ipos: int = int(random.random() * tsize)
        delta: chr = chr(int(random.random() * 255))

        return strng[0: ipos] + delta + strng[ipos + 1:]

    def mate(self,population):
        esize: int = int(self.POPULATION_SIZE * self.ELITE_RATE)
        tsize: int = len(self.TARGET)

        children = self.select_elite(population,esize)

        for i in range(esize,self.POPULATION_SIZE):
            i1: int = int(random.random() * self.POPULATION_SIZE * self.SURVIVE_RATE)
            i2: int = int(random.random() * self.POPULATION_SIZE * self.SURVIVE_RATE)
            spos: int = int(random.random() * tsize)

            strng: str = population[i1][0: spos] + population[i2][spos:]
            if(random.random() < self.MUTATION_RATE):
                strng = self.Mutation(strng)

            child = Genome(strng)
            children.append(child)

        return children

    def go(self):
        popul = self.InitializePopulation()

        for i in range(0,self.MAX_ITER):
            popul.sort()
            print("{} > {}".format(i,str(popul[0])))

            if(popul[0].fitness == 0):
                break
            popul = self.mate(popul)

    def select_elite(self,population,esize):
        children = list()
        for i in range(0,esize):
            children.append(population[i])

        return children



class Genome():
    strng = ""
    fitness = 0

    def __init__(self,strng):
        self.strng = strng
        fitness = 0
        for j in range(0,len(strng)):
            fitness += abs(ord(self.strng[j]) - ord(GAHello.TARGET[j]))

        self.fitness = fitness

    def __lt__(self,other):
        return self.fitness - other.fitness

    def __str__(self):
        return "{} {}".format(self.fitness,self.strng)

    def __getitem__(self,item):
        return self.strng[item]

谢谢你的建议.我真的是菜鸟,并且我只是训练和试验这样的算法和优化的东西来探索人工智能方法.

更新

运行的地方

if __name__ == '__main__':
    algo = GAHello()
    algo.go()

我的输出:

0 > 1122 <psá×R
1 > 1015  ÷z5A
2 > 989 "Zi±Pmê
3 > 1076  áíA
4 > 1039 #Ros
5 > 946 ×ZG¤'
6 > 774 $àP
7 > 1194 A§
 
8 > 479 @r=q^{J
9 > 778 X'YH_
10 > 642 z$oK{
...
172 > 1330 êEü
173 > 1085 Oe·×U
174 > 761 O¤+} 
175 > 903 P?-m|4
176 > 736 àPSe<1
177 > 1130 ê/*¤^
178 > 772 OS8°j
...
990 > 1017 6ó¨Q?¨í
991 > 1006 |5R·í
992 > 968 ×5Q?1V í
993 > 747 B*R·$F
994 > 607 `LaVL
995 > 744 x7ei;[
996 > 957 8/^ ¤
997 > 916 'dú8} [
998 > 892 WòeTùv6
999 > 916 g8g}à

样本输出应该是:

0 > 419 Un~?z^Kr??p┬
1 > 262 Un~?z^Kr?j?
2 > 262 Un~?z^Kr?j?
…
15 > 46 Afpdm'Ynosa"
16 > 46 Afpdm'Ynosa"
17 > 42 Afpdm'Ynoia"
18 > 27 Jfpmm↓Vopoa"
…
33 > 9 Ielmo▼Wnole"
34 > 8 Ielmo▲Vopld"
35 > 8 Ielmo▲Vopld"
…
50 > 1 Hello World"
51 > 1 Hello World"
52 > 0 Hello World!
最佳答案 我相信,您的列表排序是您的主要问题.

popul.sort()

尝试

popul.sort(key = lambda x:x.fitness)

这将按照他们的健康水平对他们进行排序,这就是我认为您想要的.

我也将所有int(random.random()* 255)更改为random.randint(30,125)以仅获取有效字符,因为我在运行时遇到了麻烦.

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读