python 用PSO 算法解决TSP 问题
时间: 2024-01-05 10:05:00 浏览: 105
以下是使用PSO算法解决TSP问题的Python代码示例:
```python
import numpy as np
# 定义TSP问题的距离矩阵
distance_matrix = np.array([[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]])
# 定义PSO算法的参数
num_particles = 50 # 粒子数量
num_iterations = 100 # 迭代次数
c1 = 2 # 加速度因子1
c2 = 2 # 加速度因子2
w = 0.7 # 惯性权重
# 初始化粒子位置和速度
particles = np.random.permutation(len(distance_matrix))
velocities = np.zeros_like(particles)
# 定义适应度函数(路径长度)
def fitness_function(particles):
total_distance = 0
for i in range(len(particles) - 1):
total_distance += distance_matrix[particles[i]][particles[i+1]]
total_distance += distance_matrix[particles[-1]][particles[0]]
return total_distance
# 初始化全局最优解和全局最优适应度
global_best_particles = particles.copy()
global_best_fitness = fitness_function(particles)
# 迭代更新粒子位置和速度
for iteration in range(num_iterations):
for i in range(num_particles):
# 更新速度
velocities[i] = (w * velocities[i] +
c1 * np.random.rand() * (global_best_particles - particles[i]) +
c2 * np.random.rand() * (particles[i] - particles[i]))
# 更新位置
particles[i] = np.roll(particles[i] + velocities[i], np.random.randint(len(distance_matrix)))
# 更新全局最优解和全局最优适应度
current_fitness = fitness_function(particles)
if current_fitness < global_best_fitness:
global_best_particles = particles.copy()
global_best_fitness = current_fitness
# 输出最优路径
print("Optimal path:", global_best_particles)
# 画出最优路径图
import matplotlib.pyplot as plt
x = [i for i in range(len(distance_matrix))]
y = [distance_matrix[global_best_particles[i]][global_best_particles[(i+1)%len(distance_matrix)]] for i in range(len(distance_matrix))]
plt.plot(x, y, 'o-')
plt.xlabel('City')
plt.ylabel('Distance')
plt.title('Optimal Path')
plt.show()
```
阅读全文