我正在尝试在python中创建一种非常简单的'进化'算法。
我最初想创建一个〜100个具有四个数值属性(A1-4(的人群,使用功能从这些属性中获得得分,然后删除得分最差的20个人。
这就是我到目前为止的
import random
population = 100
class Individual(object):
def __init__(self, a1, a2, a3, a4):
self.a1 = a1
self.a2 = a2
self.a3 = a3
self.a4 = a4
starting_population = list()
for i in range (population):
a1 = random.randint(1,10)
a2 = random.randint(1,10)
a3 = random.randint(1,10)
a4 = random.randint(1,10)
starting_population.append(Individual(a1,a2,a3,a4))
def fitness(x):
fitness = a1*a2/a3*a4
return fitness
我坚持如何将函数应用于人口列表的成员?
另外,我是Python的新手,我敢肯定我已经做了一些事情,因此任何技巧都非常感谢!
谢谢
循环有什么问题?
for person in starting_population:
person.fitness = person.a1*person.a2/person.a3*person.a4 #Add fitness to object
还要注意,操作顺序为:
((a1*a2)/a3)*a4)
如果您的意思是不同的话。您可以考虑将健身作为个人的方法:
class Individual(object):
def __init__(self, a1, a2, a3, a4):
self.a1 = a1
self.a2 = a2
self.a3 = a3
self.a4 = a4
def fitness(self,x):
fitness = self.a1*self.a2/self.a3*self.a4
return fitness
starting_population = list()
for i in range (population):
a1 = random.randint(1,10)
a2 = random.randint(1,10)
a3 = random.randint(1,10)
a4 = random.randint(1,10)
starting_population.append(Individual(a1,a2,a3,a4))
因此,您可以立即调用starting_population[i].fitness()
,或计算__init__
中的值并使其成为字段。
另一个解决方案,将代码的对象清晰度删除,以速度为numpy
数组:
import numpy.random as rnd
rnd.seed(78943598743)
starting_population=rnd.randint(1,10,size=100*4).reshape(100,4) #100 rows, 4 columns, each row a person
fitness_vector = starting_population[:,0]*starting_population[:,1]/starting_population[:,2]*starting_population[:,3]
首先,您应该使fitness
成为Individual
的方法:
import random
population = 100
class Individual(object):
def __init__(self, a1, a2, a3, a4):
self.a1 = a1
self.a2 = a2
self.a3 = a3
self.a4 = a4
def fitness(self):
fitness = self.a1*self.a2/self.a3*self.a4
return fitness
starting_population = list()
for i in range (population):
a1 = random.randint(1,10)
a2 = random.randint(1,10)
a3 = random.randint(1,10)
a4 = random.randint(1,10)
starting_population.append(Individual(a1,a2,a3,a4))
如果要删除20个得分最低的评分,请首先按健身进行排序,然后列出列表:
sorted_people = sorted(starting_population, key=lambda i:i.fitness())
fit_people = sorted_people[20:]
您也可以根据其健身的价值过滤它们,例如使用列表理解:
fit_people = [i for i in starting_population if i.fitness() > 0.5]