【发布时间】:2017-02-25 20:39:20
【问题描述】:
此代码假设减少初始游览的距离: distan(initial_tour) 我需要改变我的交换方式吗? 出了点问题,模拟退火不起作用:
def prob(currentDistance,neighbourDistance,temp):
if neighbourDistance < currentDistance:
return 1.0
else:
return math.exp( (currentDistance - neighbourDistance) / temp)
def distan(solution):
#gives the distance of solution
listax, listay = [], []
for i in range(len(solution)):
listax.append(solution[i].x)
listay.append(solution[i].y)
dists = np.linalg.norm(np.vstack([np.diff(np.array(listax)), np.diff(np.array(listay))]), axis=0)
cumsum_dist = np.cumsum(dists)
return cumsum_dist[-1]
#simulated annealing
temp = 1000000
#creating initial tour
shuffle(greedys)
initial_tour=greedys
print (distan(initial_tour))
current_best = initial_tour
best = current_best
while(temp >1 ):
#create new neighbour tour
new_solution= current_best
#Get a random positions in the neighbour tour
tourPos1=random.randrange(0, len(dfar))
tourPos2=random.randrange(0, len(dfar))
tourCity1=new_solution[tourPos1]
tourCity2=new_solution[tourPos2]
#swapping
new_solution[tourPos1]=tourCity2
new_solution[tourPos2]=tourCity1
#get distance of both current_best and its neighbour
currentDistance = distan(current_best)
neighbourDistance = distan(new_solution)
# decide if we should accept the neighbour
# random.random() returns a number in [0,1)
if prob(currentDistance,neighbourDistance,temp) > random.random():
current_best = new_solution
# keep track of the best solution found
if distan(current_best) < distan(best):
best = current_best
#Cool system
temp = temp*0.99995
print(distan(best))
【问题讨论】:
-
你能告诉我们出了什么问题吗?如果您遇到错误,请发布。
-
我会考虑使用不同的温度,可能是从 1 到 0.0000001,而不是从 1000000 到 1。就目前而言,您的代码似乎过于慷慨,无法接受恶化的解决方案。
-
在@Meerness 的评论中添加:您应该考虑距离差异的大小与温度的大小相比。当距离变化的典型大小与温度相当时,您将看到接受度的巨大变化。问题可能是您不断降低温度。您是否考虑过使用较小的特定温度集,但在每个温度下都要进行多次迭代(直到热化)?由于最初的温度很高,您可能会从一开始就离开并陷入更糟糕的状态(?)。
-
哦,我想我已经弄清楚你的问题是什么了!您的所有工作都在同一个列表中!您不是在复制列表,而是在引用它。实际上,这意味着你接受了每一个改变。尝试
new_solution = list(current_best),以便在更改之前复制列表。 -
是的,它有效!谢谢!!
标签: python traveling-salesman simulated-annealing