遗传算法python实例
时间: 2023-07-12 14:35:20 浏览: 37
以下是一个基于 Python 的遗传算法实例:
```python
import random
# 定义目标函数
def fitness_function(x):
return x * x
# 定义个体类
class Individual:
def __init__(self, chromosome):
self.chromosome = chromosome
self.fitness = fitness_function(chromosome)
# 交叉
def crossover(self, other):
pivot = random.randint(0, len(self.chromosome) - 1)
child1 = self.chromosome[:pivot] + other.chromosome[pivot:]
child2 = other.chromosome[:pivot] + self.chromosome[pivot:]
return Individual(child1), Individual(child2)
# 变异
def mutate(self):
index = random.randint(0, len(self.chromosome) - 1)
mutated = list(self.chromosome)
mutated[index] = '1' if mutated[index] == '0' else '0'
return Individual(''.join(mutated))
# 定义遗传算法类
class GeneticAlgorithm:
def __init__(self, population_size, chromosome_length, mutation_rate, crossover_rate):
self.population_size = population_size
self.chromosome_length = chromosome_length
self.mutation_rate = mutation_rate
self.crossover_rate = crossover_rate
self.population = []
# 初始化种群
def initialize_population(self):
for i in range(self.population_size):
chromosome = ''.join(random.choice(['0', '1']) for _ in range(self.chromosome_length))
individual = Individual(chromosome)
self.population.append(individual)
# 计算适应度
def calculate_fitness(self):
total_fitness = sum(individual.fitness for individual in self.population)
for individual in self.population:
individual.probability = individual.fitness / total_fitness
# 选择
def selection(self):
parents = []
for i in range(2):
probability_sum = 0
threshold = random.random()
for individual in self.population:
probability_sum += individual.probability
if probability_sum > threshold:
parents.append(individual)
break
return parents
# 进化
def evolve(self):
new_population = []
while len(new_population) < self.population_size:
parents = self.selection()
if random.random() < self.crossover_rate:
child1, child2 = parents[0].crossover(parents[1])
new_population.append(child1)
new_population.append(child2)
else:
new_population.extend(parents)
for individual in new_population:
if random.random() < self.mutation_rate:
mutated = individual.mutate()
new_population.append(mutated)
self.population = new_population[:self.population_size]
# 迭代
def run(self, generations):
self.initialize_population()
for i in range(generations):
self.calculate_fitness()
self.evolve()
return max(self.population, key=lambda x: x.fitness).chromosome
# 测试
if __name__ == '__main__':
ga = GeneticAlgorithm(population_size=100, chromosome_length=10, mutation_rate=0.1, crossover_rate=0.9)
result = ga.run(100)
print('Result:', int(result, 2))
```
这个例子中,我们尝试最大化函数 f(x) = x^2,其中 x 是二进制编码的 10 位数。运行遗传算法 100 次,最终得到的 x 值即为最优解。