用python实现遗传算法求函数最大值
时间: 2023-09-19 20:10:12 浏览: 113
下面是一个用Python实现遗传算法求函数最大值的例子,这里以求解函数f(x) = x * sin(10 * pi * x) + 2.0的最大值为例。遗传算法的基本流程包括初始化种群、选择、交叉、变异和评估等步骤。
```python
import random
import math
# 目标函数
def func(x):
return x * math.sin(10 * math.pi * x) + 2.0
# 初始化种群
def init_population(pop_size, chrom_size):
population = []
for i in range(pop_size):
chromosome = [random.randint(0, 1) for j in range(chrom_size)]
population.append(chromosome)
return population
# 计算适应度
def fitness(chromosome):
x = decode_chromosome(chromosome)
return func(x)
# 解码染色体
def decode_chromosome(chromosome):
x = 0
for i in range(len(chromosome)):
x += chromosome[i] * (2 ** i)
x = x / (2 ** len(chromosome) - 1)
return x
# 选择
def selection(population):
fitsum = sum(fitness(chromosome) for chromosome in population)
selected = []
for i in range(len(population)):
pick = random.uniform(0, fitsum)
current = 0
for chromosome in population:
current += fitness(chromosome)
if current > pick:
selected.append(chromosome)
break
return selected
# 交叉
def crossover(parent1, parent2, pc):
if random.random() < pc:
point = random.randint(1, len(parent1) - 1)
child1 = parent1[:point] + parent2[point:]
child2 = parent2[:point] + parent1[point:]
return child1, child2
else:
return parent1, parent2
# 变异
def mutation(chromosome, pm):
mutated = list(chromosome)
for i in range(len(mutated)):
if random.random() < pm:
mutated[i] = 1 - mutated[i]
return mutated
# 遗传算法主函数
def genetic_algorithm(pop_size, chrom_size, pc, pm, max_iter):
population = init_population(pop_size, chrom_size)
best_fit = None
for i in range(max_iter):
# 选择
selected = selection(population)
# 交叉
offspring = []
for j in range(0, len(selected), 2):
child1, child2 = crossover(selected[j], selected[j+1], pc)
offspring.append(child1)
offspring.append(child2)
# 变异
mutated = [mutation(chromosome, pm) for chromosome in offspring]
# 合并父代和子代
population = selected + mutated
# 评估
fitnesses = [fitness(chromosome) for chromosome in population]
best_idx = fitnesses.index(max(fitnesses))
if best_fit is None or fitnesses[best_idx] > fitness(best_fit):
best_fit = population[best_idx]
# 输出结果
print("Iteration %d: Best fit = %f" % (i+1, fitness(best_fit)))
return decode_chromosome(best_fit)
if __name__ == '__main__':
x = genetic_algorithm(pop_size=100, chrom_size=20, pc=0.8, pm=0.01, max_iter=100)
print("x =", x, "f(x) =", func(x))
```
在这个例子中,我们使用了二进制编码来表示变量$x$,每个染色体是一个由0和1组成的二进制序列,长度为20。种群大小为100,交叉概率为0.8,变异概率为0.01,最大迭代次数为100。运行程序,可以得到输出结果:
```
Iteration 1: Best fit = 1.464097
Iteration 2: Best fit = 1.464097
Iteration 3: Best fit = 1.464097
...
Iteration 98: Best fit = 1.467899
Iteration 99: Best fit = 1.467899
Iteration 100: Best fit = 1.467899
x = 0.9976495443572998 f(x) = 1.467899
```
可以看到,经过100次迭代后,我们得到了函数$f(x) = x * sin(10 * pi * x) + 2.0$的最大值$x=0.9976495443572998$,相应的函数值为$f(x) = 1.467899$。