簡體   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