遗传算法(Genetic Algorithm)是一种基于自然选择原理和自然遗传机制的启发式搜索算法。该算法通过模拟自然界中生物遗传进化的自然机制(选择、交叉和变异操作),将好的遗传基因(最优目标)不断遗传给子代,使得后代产生最优解的概率增加
示例代码如下:
# 导入所需的库
import random
import math
import numpy as np
# 定义目标函数
def f(x):
return x * math.sin(10 * math.pi * x) + 2
# 定义参数
POP_SIZE = 200 # 种群大小
GENE_SIZE = 50 # 基因长度
CROSS_RATE = 0.8 # 交叉概率
MUTATE_RATE = 0.01 # 变异概率
MAX_GEN = 1000 # 最大迭代次数
# 初始化种群
def init_pop():
pop = []
for i in range(POP_SIZE):
gene = ""
for j in range(GENE_SIZE):
gene += str(random.randint(0, 1)) # 随机生成0或1
pop.append(gene)
return pop
# 计算适应度
def fitness(pop):
fit = []
for gene in pop:
x = int(gene, 2) / (2 ** GENE_SIZE - 1) # 将二进制转换为十进制,并归一化到[0,1]区间
fit.append(f(x)) # 计算目标函数值
return fit
# 选择操作
def select(pop, fit):
new_pop = []
total_fit = sum(fit) # 计算总适应度
for i in range(POP_SIZE):
r = random.random() # 生成一个随机数
s = 0 # 累计适应度
for j in range(POP_SIZE):
s += fit[j] / total_fit # 计算每个个体的选择概率
if s >= r: # 如果累计适应度大于等于随机数,则选择该个体
new_pop.append(pop[j])
break
return new_pop
# 交叉操作
def crossover(pop):
new_pop = []
for i in range(0, POP_SIZE, 2): # 每次取两个个体进行交叉
p1 = pop[i]
p2 = pop[i + 1]
if random.random() < CROSS_RATE: # 按照交叉概率进行交叉
point = random.randint(0, GENE_SIZE - 1) # 随机选择一个交叉点
c1 = p1[:point] + p2[point:] # 生成两个新的子代
c2 = p2[:point] + p1[point:]
new_pop.append(c1)
new_pop.append(c2)
else: # 不进行交叉,则保持原样
new_pop.append(p1)
new_pop.append(p2)
return new_pop
# 变异操作
def mutate(pop):
new_pop = []
for gene in pop:
new_gene = ""
for bit in gene:
if random.random() < MUTATE_RATE: # 按照变异概率进行变异
new_bit = str(1 - int(bit)) # 将0变为1,或将1变为0
new_gene += new_bit
else: # 不进行变异,则保持原样
new_gene += bit
new_pop.append(new_gene)
return new_pop
# 主函数
def main():
pop = init_pop() # 初始化种群
for gen in range(MAX_GEN): # 迭代MAX_GEN次
fit = fitness(pop) # 计算适应度
best_fit = max(fit) # 找到最大的适应度
best_gene = pop[fit.index(best_fit)] # 找到对应的基因
best_x = int(best_gene, 2) / (2 ** GENE_SIZE - 1) # 将二进制转换为十进制,并归一化到[0,1]区间
print("Generation:", gen + 1, "Best x:", best_x, "Best f(x):", best_fit) # 打印每一代的最优解
pop = select(pop, fit) # 选择操作
pop = crossover(pop) # 交叉操作
pop = mutate(pop) # 变异操作
print("Final solution: x =", best_x, "f(x) =", best_fit) # 打印最终的解
if __name__ == "__main__":
main()