我正在尝试实现一种遗传算法来解决旅行商问题(TSP)。
我有2个班级,分别是城市和健身。
我已经完成了初始化代码。
class City:
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, city):
xDis = abs(self.x - city.x)
yDis = abs(self.y - city.y)
distance = np.sqrt((xDis ** 2) + (yDis ** 2))
return distance
def __repr__(self):
return "(" + str(self.x) + "," + str(self.y) + ")"
class Fitness:
def __init__(self, route):
self.route = route
self.distance = None
self.fitness = None
def routeDistance(self):
if self.distance == None:
pathDistance = 0.0
for i in range(0, len(self.route)):
fromCity = self.route[i]
toCity = None
if i+1 < len(self.route):
toCity = self.route[i+1]
else:
toCity = self.route[0]
pathDistance += fromCity.distance(toCity)
self.distance = pathDistance
return self.distance
def routeFitness(self):
if self.fitness == None:
self.fitness = 1 / float(self.routeDistance())
return self.fitness
def selection(population, size=None):
if size== None:
size= len(population)
matingPool = []
fitnessResults = {}
for i in range(0, size):
fitnessResults[i] = Fitness(population[i]).routeFitness()
matingPool.append(random.choice(population))
return matingPool
上面的代码只是在选择方法中随机选择一个父级。
我的问题是:如何编码使用轮盘赌选择select亲?
答案 0 :(得分:1)
from numpy.random import choice
def selection(population, size=None):
if size== None:
size= len(population)
fitnessResults = []
for i in range(0, size):
fitnessResults.append(Fitness(population[i]).routeFitness())
sum_fitness = sum(fitnessResults)
probability_lst = [f/sum_fitness for f in fitnessResults]
matingPool = choice(population, size=size, p=probability_lst)
return matingPool
答案 1 :(得分:0)
阅读this
因此,基本上,适应度值越高,被选择的机会就越高。但这就是高健身价值意味着高健身的时候。但是在TSP中,较低的适应度值更好,因此要实现这一点,我们需要实现概率与适应度值成间接比例的概念。
这是我在python中实现的一些更改
def choose_parent_using_RWS(genes, S):
P = random.uniform(0, S)
for x in genes:
P += get_fitness_value(x)
if P > S:
return x
return genes[-1]
其中S
是当前总体适应度值的倒数之和(即1 / f1 + 1 / f2 + 1 / f3 + ...)
和
get_fitness_value(x)返回距离的倒数,就像routeFitness()函数
TeeHee