遗传算法求解tsp问题python
时间: 2023-12-20 20:32:03 浏览: 84
遗传算法是一种启发式优化算法,常用于求解TSP(Traveling Salesman Problem)问题。下面是使用遗传算法求解TSP问题的Python代码示例:
```python
import random
# 定义TSP问题的距离矩阵
distance_matrix = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
# 定义遗传算法的参数
population_size = 50 # 种群大小
elite_size = 10 # 精英个体数量
mutation_rate = 0.01 # 变异率
generations = 100 # 迭代次数
# 创建一个个体(路径)
def create_individual():
individual = list(range(len(distance_matrix)))
random.shuffle(individual)
return individual
# 创建初始种群
def create_population():
population = []
for _ in range(population_size):
population.append(create_individual())
return population
# 计算路径的总距离
def calculate_fitness(individual):
total_distance = 0
for i in range(len(individual)):
from_city = individual[i]
to_city = individual[(i + 1) % len(individual)]
total_distance += distance_matrix[from_city][to_city]
return total_distance
# 选择精英个体
def select_elite(population):
population_with_fitness = [(individual, calculate_fitness(individual)) for individual in population]
population_with_fitness.sort(key=lambda x: x[1])
return [individual for individual, _ in population_with_fitness[:elite_size]]
# 交叉互换操作
def crossover(parent1, parent2):
child = [None] * len(parent1)
start_index = random.randint(0, len(parent1) - 1)
end_index = random.randint(start_index + 1, len(parent1))
child[start_index:end_index] = parent1[start_index:end_index]
for i in range(len(parent2)):
if parent2[i] not in child:
for j in range(len(child)):
if child[j] is None:
child[j] = parent2[i]
break
return child
# 变异操作
def mutate(individual):
for i in range(len(individual)):
if random.random() < mutation_rate:
j = random.randint(0, len(individual) - 1)
individual[i], individual[j] = individual[j], individual[i]
return individual
# 进化过程
def evolve(population):
elite = select_elite(population)
new_population = elite[:]
while len(new_population) < population_size:
parent1 = random.choice(elite)
parent2 = random.choice(elite)
child = crossover(parent1, parent2)
child = mutate(child)
new_population.append(child)
return new_population
# 主函数
def tsp_ga():
population = create_population()
for _ in range(generations):
population = evolve(population)
best_individual = min(population, key=calculate_fitness)
best_distance = calculate_fitness(best_individual)
return best_individual, best_distance
# 执行遗传算法求解TSP问题
best_individual, best_distance = tsp_ga()
print("Best individual:", best_individual)
print("Best distance:", best_distance)
```