Python实现模拟退火算法(SA)在TSP问题中的应用

模拟退火算法

模拟退火算法是一种简单高效的优化算法,它的灵感来源于冶炼金属的降温过程,在这个过程中热运动趋于稳定,在优化过程中就是解的收敛。同时,通过在温度高是较大可能接受劣解和温度低时几乎不接受劣解从而在一定程度上避免了陷入局部最优。因此该算法较爬山算法有了明显的突破,下面我们针对TSP问题进行代码编写。(语言:Python)

代码

导入需要的库
from random import*
import numpy as np
from math import*
from matplotlib import pyplot as plt
随机初始化100个城市的坐标
#随机初始化城市坐标
number_of_citys = 100
citys = []
for i in range(number_of_citys):
    citys.append([randint(1,100),randint(1,100)])
citys = np.array(citys)
由城市坐标构建距离矩阵
#由城市坐标计算距离矩阵
distance = np.zeros((number_of_citys,number_of_citys))
for i in range(number_of_citys):
    for j in range(number_of_citys):
        distance[i][j] = sqrt((citys[i][0]-citys[j][0])**2+(citys[i][1]-citys[j][1])**2)
初始化参数
#初始化参数
iteration1 = 2000                #外循环迭代次数
T0 = 100000                      #初始温度,取大些
Tf = 1                           #截止温度,可以不用
alpha = 0.95                     #温度更新因子
iteration2 = 10                  #内循环迭代次数
fbest = 0                        #最佳距离
初始化解
#初始化初解
x = []
for i in range(100):
    x.append(i)
np.random.shuffle(x)
x = np.array(x)
for j in range(len(x) - 1):
    fbest = fbest + distance[x[j]][x[j + 1]]
fbest = fbest + distance[x[-1]][x[0]]
xbest = x.copy()
f_now = fbest
x_now = xbest.copy()

这里的x_now和f_now是SA在运行过程中的当前解,但这个解不一定就是历史最优解,因此我们还设置了f_best和x_best用于记录历史最优解。

主循环和内部循环

主循环就是降温过程,内部循环就是在每一个温度下让算法达到平衡点。

for i in range(iteration1):
    for k in range(iteration2):
        #生成新解
        x1 = [0 for q in range(number_of_citys)]
        n1,n2 = randint(0,number_of_citys-1),randint(0,number_of_citys-1)
        n = [n1,n2]
        n.sort()
        n1,n2 = n
        #n1为0单独写
        if n1 > 0:
            x1[0:n1] = x_now[0:n1]
            x1[n1:n2+1] = x_now[n2:n1-1:-1]
            x1[n2+1:number_of_citys] = x_now[n2+1:number_of_citys]
        else:
            x1[0:n1] = x_now[0:n1]
            x1[n1:n2+1] = x_now[n2::-1]
            x1[n2+1:number_of_citys] = x_now[n2+1:number_of_citys]
        s = 0;
        for j in range(len(x1) - 1):
            s = s + distance[x1[j]][x1[j + 1]]
        s = s + distance[x1[-1]][x1[0]]
        #判断是否更新解
        if s <= f_now:
            f_now = s
            x_now = x1.copy()
        if s > f_now:
            deltaf = s - f_now
            if random() < exp(-deltaf/T0):
                f_now = s
                x_now = x1.copy()
        if s < fbest:
            fbest = s
            xbest = x1.copy()
温度更新

这里采用等比方式更新:

T0 = alpha * T0                #更新温度

如果你想把截止条件设置为最低温度,则有下面语句,不过为了更好的解,不要设置这个,通过该循环次数来调节。

    # if T0 < Tf:                  #停止准则为最低温度时可以取消注释
    #     break
打印最佳路线和最佳距离
#打印最佳路线和最佳距离
print(xbest)
print(fbest)
[74, 82, 22, 38, 95, 75, 96, 46, 79, 19, 63, 31, 18, 54, 66, 52, 37, 35, 16, 41, 60, 30, 58, 33, 23, 39, 6, 11, 4, 53, 20, 32, 81, 43, 64, 85, 51, 25, 56, 86, 77, 40, 29, 71, 93, 3, 83, 57, 65, 2, 76, 21, 88, 49, 36, 92, 69, 45, 14, 1, 72, 13, 55, 62, 7, 26, 80, 84, 10, 5, 47, 48, 8, 15, 50, 24, 98, 9, 87, 59, 91, 89, 44, 90, 78, 17, 73, 97, 12, 28, 99, 61, 42, 94, 27, 34, 68, 67, 70, 0]

884.7203239019632
Matplotlib绘制结果
#绘制结果
plt.title('SA_TSP')
plt.xlabel('x')
plt.ylabel('y')
plt.plot(citys[...,0],citys[...,1],'ob',ms = 3)
plt.plot(citys[xbest,0],citys[xbest,1])
plt.plot([citys[xbest[-1],0],citys[xbest[0],0]],[citys[xbest[-1],1],citys[xbest[0],1]],ms = 2)
plt.show()

在这里插入图片描述
可以直观看出这个结果几乎就是最优解,之前也编写过GA、禁忌搜索解决TSP,现在看来SA不仅运行速度快,效果也不错。

整体代码
from random import*
import numpy as np
from math import*
from matplotlib import pyplot as plt

#随机初始化城市坐标
number_of_citys = 100
citys = []
for i in range(number_of_citys):
    citys.append([randint(1,100),randint(1,100)])
citys = np.array(citys)

#由城市坐标计算距离矩阵
distance = np.zeros((number_of_citys,number_of_citys))
for i in range(number_of_citys):
    for j in range(number_of_citys):
        distance[i][j] = sqrt((citys[i][0]-citys[j][0])**2+(citys[i][1]-citys[j][1])**2)

#初始化参数
iteration1 = 2000                #外循环迭代次数
T0 = 100000                      #初始温度,取大些
Tf = 1                           #截止温度,可以不用
alpha = 0.95                     #温度更新因子
iteration2 = 10                  #内循环迭代次数
fbest = 0                        #最佳距离

#初始化初解
x = []
for i in range(100):
    x.append(i)
np.random.shuffle(x)
x = np.array(x)
for j in range(len(x) - 1):
    fbest = fbest + distance[x[j]][x[j + 1]]
fbest = fbest + distance[x[-1]][x[0]]
xbest = x.copy()
f_now = fbest
x_now = xbest.copy()

for i in range(iteration1):
    for k in range(iteration2):
        #生成新解
        x1 = [0 for q in range(number_of_citys)]
        n1,n2 = randint(0,number_of_citys-1),randint(0,number_of_citys-1)
        n = [n1,n2]
        n.sort()
        n1,n2 = n
        #n1为0单独写
        if n1 > 0:
            x1[0:n1] = x_now[0:n1]
            x1[n1:n2+1] = x_now[n2:n1-1:-1]
            x1[n2+1:number_of_citys] = x_now[n2+1:number_of_citys]
        else:
            x1[0:n1] = x_now[0:n1]
            x1[n1:n2+1] = x_now[n2::-1]
            x1[n2+1:number_of_citys] = x_now[n2+1:number_of_citys]
        s = 0;
        for j in range(len(x1) - 1):
            s = s + distance[x1[j]][x1[j + 1]]
        s = s + distance[x1[-1]][x1[0]]
        #判断是否更新解
        if s <= f_now:
            f_now = s
            x_now = x1.copy()
        if s > f_now:
            deltaf = s - f_now
            if random() < exp(-deltaf/T0):
                f_now = s
                x_now = x1.copy()
        if s < fbest:
            fbest = s
            xbest = x1.copy()

    T0 = alpha * T0                #更新温度

    # if T0 < Tf:                  #停止准则为最低温度时可以取消注释
    #     break

#打印最佳路线和最佳距离
print(xbest)
print(fbest)

#绘制结果
plt.title('SA_TSP')
plt.xlabel('x')
plt.ylabel('y')
plt.plot(citys[...,0],citys[...,1],'ob',ms = 3)
plt.plot(citys[xbest,0],citys[xbest,1])
plt.plot([citys[xbest[-1],0],citys[xbest[0],0]],[citys[xbest[-1],1],citys[xbest[0],1]],ms = 2)
plt.show()
  • 7
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
以下是用Python实现模拟退火算法解决TSP问题的示例代码: ```python import random import math import sys class TSP: def __init__(self, filename): self.nodes = [] self.distances = {} self.read_file(filename) def read_file(self, filename): with open(filename, "r") as f: for line in f: x, y = map(float, line.split()) self.nodes.append((x, y)) def calc_distance(self, node1, node2): return math.sqrt((node1[0] - node2[0]) ** 2 + (node1[1] - node2[1]) ** 2) def calc_distances(self): n = len(self.nodes) for i in range(n): for j in range(i + 1, n): distance = self.calc_distance(self.nodes[i], self.nodes[j]) self.distances[(i, j)] = distance self.distances[(j, i)] = distance def get_distance(self, node1, node2): if node1 > node2: node1, node2 = node2, node1 return self.distances[(node1, node2)] def get_path_distance(self, path): distance = 0 for i in range(len(path)): distance += self.get_distance(path[i], path[(i + 1) % len(path)]) return distance class SimulatedAnnealing: def __init__(self, tsp, initial_temp, cooling_rate, num_iterations): self.tsp = tsp self.initial_temp = initial_temp self.cooling_rate = cooling_rate self.num_iterations = num_iterations self.current_path = list(range(len(self.tsp.nodes))) self.best_path = self.current_path.copy() self.temperature = self.initial_temp def acceptance_probability(self, current_energy, new_energy, temperature): if new_energy < current_energy: return 1.0 else: return math.exp((current_energy - new_energy) / temperature) def run(self): for i in range(self.num_iterations): new_path = self.current_path.copy() index1 = random.randint(0, len(self.current_path) - 1) index2 = random.randint(0, len(self.current_path) - 1) new_path[index1], new_path[index2] = new_path[index2], new_path[index1] current_energy = self.tsp.get_path_distance(self.current_path) new_energy = self.tsp.get_path_distance(new_path) if self.acceptance_probability(current_energy, new_energy, self.temperature) > random.random(): self.current_path = new_path if self.tsp.get_path_distance(self.current_path) < self.tsp.get_path_distance(self.best_path): self.best_path = self.current_path.copy() self.temperature *= self.cooling_rate return self.best_path if __name__ == "__main__": tsp = TSP(sys.argv[1]) tsp.calc_distances() sa = SimulatedAnnealing(tsp, 100000.0, 0.99, 10000) best_path = sa.run() print("Best path found: ", best_path) print("Path distance: ", tsp.get_path_distance(best_path)) ``` 在此示例,`TSP`类用于读取TSP问题的节点坐标,并计算节点之间的距离。`SimulatedAnnealing`类实现模拟退火算法,包括计算能量、接受概率和运行算法的主循环。最后,我们使用这些类来解决TSP问题,找到最短的路径并输出结果。 要运行脚本,请在命令行输入以下命令: ```bash python tsp.py <tsp_file> ``` 其 `<tsp_file>` 是包含节点坐标的文件的路径。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

iπ弟弟

如果可以的话,请杯咖啡吧!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值