基于Python的模拟退火算法实现进化算法求解TSP问题的完整代码。代码中生成了30个坐标固定的城市,并求解从点1出发,经过其他29个点后的最优路径(最优路径图、最优路径编号序列、最优路径长度三部分内容)
时间: 2024-03-20 18:45:03 浏览: 54
基于模拟退火算法的TSP问题求解(代码完整,数据齐全)
好的,以下是基于Python的模拟退火算法实现进化算法求解TSP问题的完整代码,共三部分:
1. TSP问题数据生成与可视化代码(生成30个坐标固定的城市):
```python
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)
# 生成30个坐标固定的城市
num_cities = 30
coord_x = np.random.rand(num_cities)
coord_y = np.random.rand(num_cities)
# 可视化城市
fig, ax = plt.subplots()
ax.scatter(coord_x, coord_y)
for i in range(num_cities):
ax.annotate(str(i+1), (coord_x[i]+0.01, coord_y[i]+0.01))
plt.show()
```
2. 模拟退火算法求解TSP问题代码:
```python
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)
# 生成30个坐标固定的城市
num_cities = 30
coord_x = np.random.rand(num_cities)
coord_y = np.random.rand(num_cities)
# 计算距离矩阵
distance_matrix = np.zeros((num_cities, num_cities))
for i in range(num_cities):
for j in range(num_cities):
if i != j:
distance_matrix[i][j] = np.sqrt((coord_x[i]-coord_x[j])**2 + (coord_y[i]-coord_y[j])**2)
# 模拟退火算法参数
initial_temperature = 1000
cooling_rate = 0.999
num_iterations = 10000
# 初始化当前解
current_solution = np.arange(num_cities)
np.random.shuffle(current_solution)
current_length = 0
for i in range(num_cities-1):
current_length += distance_matrix[current_solution[i]][current_solution[i+1]]
current_length += distance_matrix[current_solution[-1]][current_solution[0]]
# 初始化最优解
best_solution = current_solution.copy()
best_length = current_length
# 模拟退火算法求解TSP问题
for i in range(num_iterations):
# 生成新解
new_solution = current_solution.copy()
index1, index2 = np.random.choice(num_cities, size=2, replace=False)
new_solution[index1], new_solution[index2] = new_solution[index2], new_solution[index1]
# 计算新解长度
new_length = 0
for j in range(num_cities-1):
new_length += distance_matrix[new_solution[j]][new_solution[j+1]]
new_length += distance_matrix[new_solution[-1]][new_solution[0]]
# 判断是否接受新解
delta = new_length - current_length
if delta < 0 or np.exp(-delta/initial_temperature) > np.random.rand():
current_solution = new_solution.copy()
current_length = new_length
if current_length < best_length:
best_solution = current_solution.copy()
best_length = current_length
# 降温
initial_temperature *= cooling_rate
# 可视化最优路径
fig, ax = plt.subplots()
ax.scatter(coord_x, coord_y)
for i in range(num_cities):
ax.annotate(str(best_solution[i]+1), (coord_x[best_solution[i]]+0.01, coord_y[best_solution[i]]+0.01))
for i in range(num_cities-1):
ax.plot([coord_x[best_solution[i]], coord_x[best_solution[i+1]]], [coord_y[best_solution[i]], coord_y[best_solution[i+1]]], 'r')
ax.plot([coord_x[best_solution[-1]], coord_x[best_solution[0]]], [coord_y[best_solution[-1]], coord_y[best_solution[0]]], 'r')
plt.show()
print('最优路径编号序列:', best_solution+1)
print('最优路径长度:', best_length)
```
3. 进化算法求解TSP问题代码:
```python
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)
# 生成30个坐标固定的城市
num_cities = 30
coord_x = np.random.rand(num_cities)
coord_y = np.random.rand(num_cities)
# 计算距离矩阵
distance_matrix = np.zeros((num_cities, num_cities))
for i in range(num_cities):
for j in range(num_cities):
if i != j:
distance_matrix[i][j] = np.sqrt((coord_x[i]-coord_x[j])**2 + (coord_y[i]-coord_y[j])**2)
# 进化算法参数
pop_size = 100
elite_size = 10
mutation_rate = 0.1
num_generations = 1000
# 初始化种群
def create_individual():
individual = np.arange(num_cities)
np.random.shuffle(individual)
return individual
population = [create_individual() for i in range(pop_size)]
# 进化算法求解TSP问题
for i in range(num_generations):
# 计算适应度
fitness = np.zeros(pop_size)
for j in range(pop_size):
length = 0
for k in range(num_cities-1):
length += distance_matrix[population[j][k]][population[j][k+1]]
length += distance_matrix[population[j][-1]][population[j][0]]
fitness[j] = 1/length
# 选择精英个体
elite_indices = np.argsort(fitness)[::-1][:elite_size]
next_population = [population[index] for index in elite_indices]
# 选择并交叉产生新个体
while len(next_population) < pop_size:
parent_indices = np.random.choice(elite_size, size=2, replace=False)
parent1, parent2 = population[elite_indices[parent_indices[0]]], population[elite_indices[parent_indices[1]]]
child = np.zeros(num_cities, dtype=int)
start_index, end_index = np.random.choice(num_cities, size=2, replace=False)
if start_index > end_index:
start_index, end_index = end_index, start_index
child[start_index:end_index+1] = parent1[start_index:end_index+1]
remaining_indices = [index for index in range(num_cities) if parent2[index] not in child]
remaining_values = [parent2[index] for index in remaining_indices]
child[remaining_indices] = remaining_values
next_population.append(child)
# 变异
for j in range(1, pop_size):
if np.random.rand() < mutation_rate:
index1, index2 = np.random.choice(num_cities, size=2, replace=False)
next_population[j][index1], next_population[j][index2] = next_population[j][index2], next_population[j][index1]
population = next_population
# 计算适应度
fitness = np.zeros(pop_size)
for i in range(pop_size):
length = 0
for j in range(num_cities-1):
length += distance_matrix[population[i][j]][population[i][j+1]]
length += distance_matrix[population[i][-1]][population[i][0]]
fitness[i] = 1/length
# 找到最优个体
best_index = np.argmax(fitness)
best_solution = population[best_index]
best_length = 1/fitness[best_index]
# 可视化最优路径
fig, ax = plt.subplots()
ax.scatter(coord_x, coord_y)
for i in range(num_cities):
ax.annotate(str(best_solution[i]+1), (coord_x[best_solution[i]]+0.01, coord_y[best_solution[i]]+0.01))
for i in range(num_cities-1):
ax.plot([coord_x[best_solution[i]], coord_x[best_solution[i+1]]], [coord_y[best_solution[i]], coord_y[best_solution[i+1]]], 'r')
ax.plot([coord_x[best_solution[-1]], coord_x[best_solution[0]]], [coord_y[best_solution[-1]], coord_y[best_solution[0]]], 'r')
plt.show()
print('最优路径编号序列:', best_solution+1)
print('最优路径长度:', best_length)
```
以上三部分代码连起来就是完整的基于Python的模拟退火算法实现进化算法求解TSP问题的代码。
阅读全文