我正在努力创造一个非常简单的“进化”' python中的算法。
我最初想要创建一个拥有四个数字属性(a1-4)的约100个人口,使用一个函数从这些属性中获得一个分数,然后删除最差得分的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非常陌生,而且我确定我做了很多事情,所以任何提示都非常感谢!
谢谢
答案 0 :(得分:1)
循环有什么问题?
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]
答案 1 :(得分:0)
首先,您应该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]