繁体   English   中英

Python中解决旅行商问题的模拟退火算法

[英]Simulated annealing algorithm to solve the traveling salesman problem in Python

所以我试图使用模拟退火解决旅行商问题。 我得到一个 100x100 矩阵,其中包含每个城市之间的距离,例如,[0][0] 将包含 0,因为第一个城市与其自身之间的距离为 0,[0][1] 包含第一个城市之间的距离和第二个城市等等。

我的问题是,我编写的代码并没有最小化旅行距离,它被困在一个数字范围内并且在温度达到 0 之前永远不会正确最小化。我尝试用爬山算法做同样的问题,它工作得很好,但我似乎无法让它与模拟退火一起工作。 有人可以帮我看看我做错了什么吗?

Mat = distancesFromCoords() #returns the 100x100 matrix with distances
T = 10000 #temperature
Alpha = 0.98 #decreasing factor
X = [i for i in range(99)] #random initial tour
random.shuffle(X)
X.append(X[0])    

while T > 0.01:
    Z = nuevoZ(X,Mat) #Best current solution
    Xp = copy.deepcopy(X)          
    a = random.sample(range(1,98),2)
    Xp[a[0]], Xp[a[1]] = Xp[a[1]],Xp[a[0]]   
    Zp = nuevoZ(Xp,Mat)  #Probable better solution

    decimal.setcontext(decimal.Context(prec=5))
    deltaZ = Zp - Z
    Prob = decimal.Decimal(-deltaZ/T).exp()

    print("probabilidad: ", Prob)
    print("Temperatura: ",T)
    print("Z: ",Z)
    print("Zp: ",Zp)
    print("\n")

    if Zp < Z:
        X = Xp
        T = T*Alpha
    else:
        num = randint(0,1)
        if num<Prob:
            X = copy.copy(Xp)
            T = T*Alpha

算法中用到的函数:

def nuevoZ(X, Mat):
Z = 0
for i in range(len(X)-1):
    Z = Z + Mat[X[i]][X[i+1]] 
return Z  #returns a new solution given the tour X and the City Matrix.


def distancesFromCoords():  #gets the matrix from a text file.
f = open('kroA100.tsp')
data = [line.replace("\n","").split(" ")[1:] for line in f.readlines()[6:106]]
coords =  list(map(lambda x: [float(x[0]),float(x[1])], data))
distances = []
for i in range(len(coords)):
    row = []
    for j in range(len(coords)):
        row.append(math.sqrt((coords[i][0]-coords[j][0])**2 + (coords[i][1]-coords[j][1])**2))
    distances.append(row)
return distances

https://pypi.org/project/frigidum/

包含 TSP(442 个城市)的示例。

在 SA 找到潜在解决方案后使用 local_search_2opt 是一种很好的做法(如示例中所示)。

如果不收敛:

  1. 检查接受函数确实总是以概率接受较短和较长的解决方案
  2. 检查在前几个提案中,大多数提案都被接受,即使它们更糟。 如果不是这种情况,则初始温度不够高。
  3. 检查建议是否有效。 您可能希望打印/调试一轮中每个提案的全局最小值差异。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM