帮我举一个遗传算法的例子,并用python生成代码
时间: 2024-01-14 16:42:08 浏览: 69
一个经典的遗传算法示例是TSP(旅行商问题)。TSP是一个NP难题,因此使用遗传算法来解决它是非常有效的。
以下是一个使用Python实现TSP遗传算法的示例代码:
```python
import random
import numpy as np
# 遗传算法类
class GeneticAlgorithm:
def __init__(self, population_size, mutation_rate, elitism):
self.population_size = population_size
self.mutation_rate = mutation_rate
self.elitism = elitism
# 初始化种群
def init_population(self, chromosome_length):
population = []
for i in range(self.population_size):
chromosome = [i for i in range(chromosome_length)]
random.shuffle(chromosome)
population.append(chromosome)
return population
# 计算适应度
def calculate_fitness(self, chromosome, distance_matrix):
fitness = 0
for i in range(len(chromosome) - 1):
fitness += distance_matrix[chromosome[i]][chromosome[i+1]]
fitness += distance_matrix[chromosome[-1]][chromosome[0]]
return fitness
# 选择
def selection(self, population, distance_matrix):
fitnesses = [self.calculate_fitness(chromosome, distance_matrix) for chromosome in population]
sorted_indexes = np.argsort(fitnesses)
sorted_population = [population[i] for i in sorted_indexes]
return sorted_population[:self.elitism] + random.choices(sorted_population[self.elitism:], k=self.population_size-self.elitism)
# 交叉
def crossover(self, parent1, parent2):
child = [-1] * len(parent1)
start = random.randint(0, len(parent1) - 1)
end = random.randint(0, len(parent1) - 1)
if start > end:
start, end = end, start
for i in range(start, end+1):
child[i] = parent1[i]
j = 0
for i in range(len(parent2)):
if child[j] == -1:
if parent2[i] not in child:
child[j] = parent2[i]
j += 1
else:
j += 1
return child
# 变异
def mutate(self, chromosome):
if random.random() < self.mutation_rate:
index1 = random.randint(0, len(chromosome) - 1)
index2 = random.randint(0, len(chromosome) - 1)
chromosome[index1], chromosome[index2] = chromosome[index2], chromosome[index1]
# 运行遗传算法
def run(self, distance_matrix, num_generations):
population = self.init_population(len(distance_matrix))
for i in range(num_generations):
population = self.selection(population, distance_matrix)
new_population = []
while len(new_population) < self.population_size:
parent1, parent2 = random.sample(population, 2)
child = self.crossover(parent1, parent2)
self.mutate(child)
new_population.append(child)
population = new_population
best_individual = min(population, key=lambda chromosome: self.calculate_fitness(chromosome, distance_matrix))
return best_individual, self.calculate_fitness(best_individual, distance_matrix)
# 测试
if __name__ == '__main__':
distance_matrix = [
[0, 2, 9, 10],
[1, 0, 6, 4],
[15, 7, 0, 8],
[6, 3, 12, 0]
]
ga = GeneticAlgorithm(population_size=100, mutation_rate=0.01, elitism=2)
best_individual, best_fitness = ga.run(distance_matrix, num_generations=1000)
print('Best individual:', best_individual)
print('Best fitness:', best_fitness)
```
这个代码实现了一个遗传算法来解决TSP问题。它首先初始化一个种群,然后在每一代中进行选择、交叉和变异操作。最后,它返回最佳个体和适应度。
阅读全文