遗传算法写一个具体的函数计算例子,除了y=x的平方这个函数,并写明具体的计算和迭代过程
时间: 2024-09-28 16:10:42 浏览: 34
遗传算法是一种模拟自然选择和遗传机制的优化搜索算法,常用于解决复杂的非线性优化问题。下面是一个简单的遗传算法示例,我们尝试找到使得 `f(x) = a * x^2 + b` 的最小值,假设我们不是寻找 `y=x^2` 而是有一个自定义的目标函数。
首先,我们需要定义以下几个步骤:
1. 初始化种群:生成一组随机解(也称为个体),每个解表示为一组实数 `[x, y]`,例如 `[x1, f(x1)], [x2, f(x2)]` 等。
```python
import numpy as np
def create_population(size, bounds):
population = []
for _ in range(size):
x = np.random.uniform(bounds[0][0], bounds[0][1])
y = a * x**2 + b
population.append([x, y])
return population
```
2. 计算适应度:对每个个体计算目标函数值,适应度越高,个体越优秀。
```python
def calculate_fitness(individuals, target_function):
fitness = [target_function(individual[0]) for individual in individuals]
return fitness
```
3. 选择操作:选择部分适应度较高的个体作为父母进入下一代。
```python
def selection(population, fitness, ratio):
selected = []
while len(selected) < len(population):
parent_indices = np.argsort(fitness)[:int(len(population) * ratio)]
selected.extend(population[parent_indices])
return selected
```
4. 交叉(Crossover):创建新的个体通过合并两个父母的基因(这里指解的x坐标)。
```python
def crossover(parents, crossover_rate):
offspring = []
for _ in range(int(len(parents) / 2)):
parent1, parent2 = np.random.choice(parents, size=2)
if np.random.rand() < crossover_rate:
# 染色体交叉
cut_point = np.random.randint(0, len(parent1[0]))
child_x = np.concatenate((parent1[0][:cut_point], parent2[0][cut_point:]))
else:
child_x = parent1[0]
child_y = a * child_x**2 + b
offspring.append([child_x, child_y])
return offspring
```
5. 变异(Mutation):引入随机变化以增加多样性。
```python
def mutation(offspring, mutation_rate):
mutated_offspring = []
for child in offspring:
if np.random.rand() < mutation_rate:
child_x = np.random.uniform(bounds[0][0], bounds[0][1])
child_y = a * child_x**2 + b
mutated_offspring.append(child)
return mutated_offspring
```
6. 迭代:将新产生的后代替换原始种群,然后再次循环上述步骤直到达到预定的停止条件(如达到最大迭代次数或适应度达到某个阈值)。
整个流程如下:
```python
# 参数设置
population_size = 100
max_iterations = 1000
crossover_rate = 0.8
mutation_rate = 0.05
fitness_target_function = lambda x: a * x**2 + b
bounds = [[-10, 10]] # 假设a和b已知
for iteration in range(max_iterations):
population = create_population(population_size, bounds)
fitness = calculate_fitness(population, fitness_target_function)
parents = selection(population, fitness, 0.7) # 保留70%的最优个体
offspring = crossover(parents, crossover_rate)
offspring = mutation(offspring, mutation_rate)
population = offspring
# 输出当前最佳解
best_solution = min(population, key=lambda x: x[1])
print(f"Iteration {iteration+1}: Best solution = [{best_solution[0]:.2f}], Fitness = {best_solution[1]}")
```
阅读全文