基于Python的粒子群算法实现进化算法求解TSP问题的完整代码。代码中从编号1-30,生成了30个坐标固定的城市,并求解从点1出发,经过其他29个点后的最优路径(包含最优路径图、最优路径编号序列、最优路径长度三部分内容)。
时间: 2024-03-18 09:39:12 浏览: 55
以下是基于Python的粒子群算法实现进化算法求解TSP问题的完整:
```python
import numpy as np
import matplotlib.pyplot as plt
# 定义城市数量
num_cities = 30
# 定义城市坐标
cities = np.array([[ 37, 52], [ 49, 49], [ 52, 64], [ 20, 26], [ 40, 30],
[ 21, 47], [ 17, 63], [ 31, 62], [ 52, 33], [ 51, 21],
[ 42, 41], [ 31, 32], [ 5, 25], [ 12, 42], [ 36, 16],
[ 52, 41], [ 27, 23], [ 17, 33], [ 13, 13], [ 57, 58],
[ 62, 42], [ 42, 57], [ 16, 57], [ 8, 52], [ 7, 38],
[ 27, 68], [ 30, 48], [ 43, 67], [ 58, 48], [ 58, 27]])
# 定义距离矩阵
dist_matrix = np.zeros((num_cities, num_cities))
for i in range(num_cities):
for j in range(num_cities):
dist_matrix[i][j] = np.sqrt((cities[i][0]-cities[j][0])**2 + (cities[i][1]-cities[j][1])**2)
# 定义粒子群算法相关参数
num_particles = 100
max_iter = 100
w = 0.8
c1 = 1.5
c2 = 1.5
# 初始化粒子群位置和速度
particles_pos = np.zeros((num_particles, num_cities), dtype=int)
particles_vel = np.zeros((num_particles, num_cities), dtype=int)
for i in range(num_particles):
particles_pos[i] = np.random.permutation(num_cities)
particles_vel[i] = np.random.permutation(num_cities)
# 定义全局最优解及其路径长度
global_best_pos = np.zeros(num_cities, dtype=int)
global_best_cost = float('inf')
# 迭代寻优
for iter in range(max_iter):
# 计算每个粒子的路径长度
particles_cost = np.zeros(num_particles)
for i in range(num_particles):
for j in range(num_cities-1):
particles_cost[i] += dist_matrix[particles_pos[i][j]][particles_pos[i][j+1]]
particles_cost[i] += dist_matrix[particles_pos[i][num_cities-1]][particles_pos[i][0]]
# 更新全局最优解
if particles_cost[i] < global_best_cost:
global_best_pos = particles_pos[i].copy()
global_best_cost = particles_cost[i]
# 更新每个粒子的速度和位置
for i in range(num_particles):
r1, r2 = np.random.rand(), np.random.rand()
particles_vel[i] = w*particles_vel[i] + c1*r1*(particles_pos[i]-particles_pos[i]) + c2*r2*(global_best_pos-particles_pos[i])
particles_pos[i] = np.argsort(particles_vel[i])
# 输出每次迭代的全局最优解
print('Iteration:', iter+1, 'Global Best Cost:', global_best_cost)
# 绘制最优路径图
x = cities[:,0]
y = cities[:,1]
plt.plot(x[global_best_pos], y[global_best_pos], 'r', alpha=0.5)
plt.scatter(x, y)
plt.show()
# 输出最优路径编号序列和路径长度
print('Optimal Path:', global_best_pos+1)
print('Optimal Path Length:', global_best_cost)
```
运行以上代码,可以得到最优路径图、最优路径编号序列和最优路径长度三部分结果。
阅读全文