【问题标题】:Simulated annealing algorithm to solve the traveling salesman problem in Python用Python模拟退火算法解决旅行商问题
【发布时间】:2019-07-27 09:16:33
【问题描述】:

所以我尝试使用模拟退火来解决旅行商问题。我得到一个 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

【问题讨论】:

标签: python algorithm traveling-salesman simulated-annealing


【解决方案1】:

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

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

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

如果不收敛:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 2020-01-02
    • 2019-11-16
    • 2021-07-09
    • 2012-07-27
    相关资源
    最近更新 更多