用于模拟Python中的旅行商问题的模拟退火算法

问题描述 投票:0回答:1

因此,我正在尝试使用模拟退火解决旅行商问题。我得到一个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个回答
0
投票

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

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

在SA找到可能的解决方案之后,使用local_search_2opt是一个好习惯(如示例)。

如果不收敛:

  1. 检查确实接受函数实际上是[[总是接受较短和较长的解决方案]
  2. 检查前几项建议中,即使较差的建议也被接受。如果不是这种情况,则初始温度不够高。
  3. 检查提议是否有效。您可能希望在一轮中打印/调试每个提案的全局最小值差异。
© www.soinside.com 2019 - 2024. All rights reserved.