Python 遗传算法优化程序示例
遗传算法是一种优化算法,它模拟自然界中的生物进化过程,通过不断的选择、交叉和变异,逐步寻找到问题的最优解。下面是一个简单的 Python 遗传算法优化程序的示例:
import random
# 定义优化目标函数,这里以简单的函数 y = x^2 为例
def objective_function(x):
return x ** 2
# 定义个体类,包含基因序列和适应度值两个属性
class Individual:
def __init__(self, gene_length):
self.gene = [random.randint(0, 1) for _ in range(gene_length)]
self.fitness = 0
def __repr__(self):
return ''.join(str(x) for x in self.gene)
# 定义遗传算法类
class GeneticAlgorithm:
def __init__(self, population_size, gene_length, crossover_rate, mutation_rate):
self.population_size = population_size
self.gene_length = gene_length
self.crossover_rate = crossover_rate
self.mutation_rate = mutation_rate
self.population = [Individual(gene_length) for _ in range(population_size)]
# 计算个体适应度值
def calculate_fitness(self):
for individual in self.population:
x = int(''.join(str(x) for x in individual.gene), 2)
individual.fitness = objective_function(x)
# 选择操作
def selection(self):
parents = []
# 轮盘赌选择
total_fitness = sum(individual.fitness for individual in self.population)
for _ in range(self.population_size):
pick = random.uniform(0, total_fitness)
current = 0
for individual in self.population:
current += individual.fitness
if current > pick:
parents.append(individual)
break
return parents
# 交叉操作
def crossover(self, parent1, parent2):
child1 = Individual(self.gene_length)
child2 = Individual(self.gene_length)
if random.uniform(0, 1) < self.crossover_rate:
crossover_point = random.randint(1, self.gene_length - 1)
child1.gene = parent1.gene[:crossover_point] + parent2.gene[crossover_point:]
child2.gene = parent2.gene[:crossover_point] + parent1.gene[crossover_point:]
else:
child1.gene = parent1.gene
child2.gene = parent2.gene
return child1, child2
# 变异操作
def mutation(self, child):
for i in range(self.gene_length):
if random.uniform(0, 1) < self.mutation_rate:
child.gene[i] = 1 - child.gene[i]
# 进化过程
def evolve(self, generations):
for i in range(generations):
self.calculate_fitness()
parents = self.selection()
new_population = []
for j in range(0, self.population_size - 1, 2):
parent1 = parents[j]
parent2 = parents[j+1]
child1, child2 = self.crossover(parent1, parent2)
self.mutation(child1)
self.mutation(child2)
new_population.append(child1)
new_population.append(child2)
self.population = new_population
# 返回种群中适应度最高的个体
best_individual = max(self.population, key=lambda individual: individual.fitness)
return best_individual
# 测试
ga = GeneticAlgorithm(50, 5, 0.8, 0.01)
print(ga.evolve(100))
这个程序使用遗传算法来优化一个简单的函数 y = x^2,其中 x 是一个二进制数。在程序中,个体是由一个由 0 和 1 组成的基因序列和一个适应度值组成的类。遗传算法类中包含计算适应度值、选择、交叉和变异等操作。在测试中,我们使用种群大小为 50,基因长度为 5,交叉率为 0.8,变异率为 0.01,进行了 100 代的进化。最终得到的最优个体的基因序列对应的二进制数为 31,即 y = 961,是函数的最优解。
原文地址: https://www.cveoy.top/t/topic/nCOr 著作权归作者所有。请勿转载和采集!