要使用Python解决旅行商问题(TSP)问题,可以使用遗传算法。下面是一个简单的步骤指南:
import random
import numpy as np
cities = np.array([[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]])
population_size = 100
crossover_rate = 0.8
mutation_rate = 0.01
population = [np.random.permutation(len(cities)) for _ in range(population_size)]
def fitness(individual):
total_distance = 0
for i in range(len(individual)-1):
city1 = cities[individual[i]]
city2 = cities[individual[i+1]]
total_distance += np.linalg.norm(city1 - city2)
return total_distance
def selection(population, fitness):
total_fitness = sum(fitness)
probabilities = [f/total_fitness for f in fitness]
parents = np.random.choice(population, size=2, p=probabilities)
return parents
def crossover(parents):
parent1, parent2 = parents
point = random.randint(0, len(parent1))
child = np.zeros(len(parent1))
child[:point] = parent1[:point]
for gene in parent2:
if gene not in child:
child[point] = gene
point += 1
return child
def mutation(child):
if random.random() < mutation_rate:
point1, point2 = random.sample(range(len(child)), 2)
child[point1], child[point2] = child[point2], child[point1]
return child
for generation in range(max_generations):
fitness_values = [fitness(individual) for individual in population]
best_individual = population[np.argmin(fitness_values)]
new_population = [best_individual]
while len(new_population) < population_size:
parents = selection(population, fitness_values)
child = crossover(parents)
child = mutation(child)
new_population.append(child)
population = new_population
best_individual = population[np.argmin(fitness_values)]
best_path = [cities[i] for i in best_individual]
print("Best path:", best_path)
这只是一个简单的示例,可以根据具体的需求进行修改和扩展。