python遗传算法示例
时间: 2023-08-25 15:19:03 浏览: 105
遗传算法简单示例.ppt
遗传算法是一种模拟自然界生物遗传学和生物进化论的并行随机搜索最优化方法。它具有智能式搜索、渐进式优化、全局最优解、黑箱式结构、通用性强和并行式算法等特征。
下面是一个示例的Python代码,演示了如何使用遗传算法解决一个函数优化问题:
```python
import numpy as np
# 定义适应度函数(目标函数)
def fitness_func(x):
return -x**2 + 2*x + 3
# 定义遗传算法的相关参数
pop_size = 50 # 种群大小
chrom_length = 10 # 染色体长度(二进制编码位数)
pc = 0.6 # 交叉概率
pm = 0.01 # 变异概率
max_iter = 100 # 最大迭代次数
# 初始化种群
population = np.random.randint(2, size=(pop_size, chrom_length))
# 开始迭代
for iter in range(max_iter):
# 计算适应度值
fitness = fitness_func(population)
# 选择操作(轮盘赌选择)
cum_sum = np.cumsum(fitness)
cum_sum /= cum_sum[-1]
new_population = []
for _ in range(pop_size):
rand_num = np.random.rand()
for i in range(pop_size):
if rand_num <= cum_sum[i]:
new_population.append(population[i])
break
# 交叉操作
for i in range(0, pop_size, 2):
if np.random.rand() < pc:
cross_point = np.random.randint(1, chrom_length)
temp1 = np.concatenate((new_population[i][:cross_point], new_population[i+1][cross_point:]))
temp2 = np.concatenate((new_population[i+1][:cross_point], new_population[i][cross_point:]))
new_population[i = temp1
new_population[i+1 = temp2
# 变异操作
for i in range(pop_size):
if np.random.rand() < pm:
mutate_point = np.random.randint(chrom_length)
new_population[i][mutate_point = 1 - new_population[i][mutate_point]
population = new_population
# 找出最优解
best_index = np.argmax(fitness)
best_solution = population<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [遗传算法python(含例程代码与详解)](https://blog.csdn.net/qq_38048756/article/details/109256062)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文