【机器学习|学习笔记】遗传算法(Genetic Algorithm, GA)的起源、发展、应用和未来前景!并附实现代码。(二)
【机器学习|学习笔记】遗传算法(Genetic Algorithm, GA)的起源、发展、应用和未来前景!并附实现代码。(二)
文章目录
欢迎铁子们点赞、关注、收藏!
祝大家逢考必过!逢投必中!上岸上岸上岸!upupup
大多数高校硕博生毕业要求需要参加学术会议,发表EI或者SCI检索的学术论文会议论文。详细信息可关注VX “
学术会议小灵通
”或参考学术信息专栏:https://blog.youkuaiyun.com/2401_89898861/article/details/146340044
遗传算法的Python实现
下面是一个简单的遗传算法实现,用于求解一个简单的数学优化问题,目标是最大化 f ( x ) = x 2 f(x) = x^2 f(x)=x2,在区间 [ 0 , 31 ] [0, 31] [0,31]内。
import random
# 目标函数:f(x) = x^2
def fitness(x):
return x**2
# 二进制编码解码
def decode(binary):
return int(binary, 2)
def encode(x, length=5):
return format(x, f"0{length}b")
# 选择操作:轮盘赌选择
def selection(population):
total_fitness = sum(fitness(decode(individual)) for individual in population)
pick = random.uniform(0, total_fitness)
current = 0
for individual in population:
current += fitness(decode(individual))
if current > pick:
return individual
# 交叉操作:单点交叉
def crossover(parent1, parent2):
crossover_point = random.randint(1, len(parent1)-1)
offspring1 = parent1[:crossover_point] + parent2[crossover_point:]
offspring2 = parent2[:crossover_point] + parent1[crossover_point:]
return offspring1, offspring2
# 变异操作:位翻转
def mutation(offspring, mutation_rate=0.01):
mutated = list(offspring)
for i in range(len(mutated)):
if random.random() < mutation_rate:
mutated[i] = '1' if mutated[i] == '0' else '0'
return ''.join(mutated)
# 主遗传算法函数
def genetic_algorithm(population_size=10, generations=100, mutation_rate=0.01):
population = [encode(random.randint(0, 31)) for _ in range(population_size)]
for generation in range(generations):
new_population = []
for _ in range(population_size//2):
parent1 = selection(population)
parent2 = selection(population)
offspring1, offspring2 = crossover(parent1, parent2)
new_population.append(mutation(offspring1, mutation_rate))
new_population.append(mutation(offspring2, mutation_rate))
population = new_population
best_individual = max(population, key=lambda ind: fitness(decode(ind)))
print(f"Generation {generation+1}: Best fitness = {fitness(decode(best_individual))}, x = {decode(best_individual)}")
return population
# 运行遗传算法
genetic_algorithm(population_size=20, generations=50, mutation_rate=0.05)
代码解释
1. 初始化种群:
- 在
genetic_algorithm
函数中,我们随机生成了一组二进制编码的个体作为种群,每个个体代表一个解(在 [0, 31] 区间内的整数)。
2. 适应度评估:
fitness
函数计算每个个体的适应度,这里是 f ( x ) = x 2 f(x) = x^2 f(x)=x2。
3. 选择:
selection
函数使用轮盘赌选择策略,选择适应度较高的个体。
4. 交叉:
crossover
函数使用单点交叉操作,生成两个后代个体。
5. 变异:
mutation
函数实现基因的位翻转操作,模拟突变现象。
6. 运行过程:
- 在每一代中,选择适应度较高的个体进行交叉和变异,生成新一代种群。并输出每代的最佳解。
总结
- 遗传算法作为一种启发式的优化算法,在许多领域都有广泛应用,尤其是在处理复杂、非线性、多峰的优化问题时。
- 随着人工智能、深度学习等技术的发展,遗传算法将继续演化,与其他算法结合,推动更多领域的应用。
欢迎铁子们点赞、关注、收藏!
祝大家逢考必过!逢投必中!上岸上岸上岸!upupup
大多数高校硕博生毕业要求需要参加学术会议,发表EI或者SCI检索的学术论文会议论文。详细信息可关注VX “
学术会议小灵通
”或参考学术信息专栏:https://blog.youkuaiyun.com/2401_89898861/article/details/146340044