要使用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)
這只是一個簡單的示例,可以根據具體的需求進行修改和擴展。