在这个例子中,我们尝试最小化一个简单的二元函数,即 \(f(x, y) = x^2 + y^2\)。
import numpy as np
# 定义目标函数
def objective_function(x, y):
return x**2 + y**2
# 定义遗传算法
def genetic_algorithm(population_size, num_generations, crossover_rate, mutation_rate):
# 初始化种群
population = np.random.rand(population_size, 2)
for generation in range(num_generations):
# 计算适应度
fitness = objective_function(population[:, 0], population[:, 1])
# 选择
selected_indices = np.random.choice(population_size, size=population_size, p=fitness/fitness.sum())
# 交叉
crossover_mask = np.random.rand(population_size) < crossover_rate
crossover_pairs = np.array(list(zip(selected_indices[::2], selected_indices[1::2])))
crossover_points = np.random.randint(0, 2, size=(len(crossover_pairs), 2))
population[crossover_pairs[crossover_mask]] = np.column_stack((
np.concatenate((population[crossover_pairs[crossover_mask]][:, 0][:, None], population[crossover_pairs[crossover_mask ^ 1]][:, 0][:, None]), axis=1)[np.arange(len(crossover_pairs))[crossover_mask], np.concatenate(crossover_points[:, :1])]),
np.concatenate((population[crossover_pairs[crossover_mask]][:, 1][:, None], population[crossover_pairs[crossover_mask ^ 1]][:, 1][:, None]), axis=1)[np.arange(len(crossover_pairs))[crossover_mask], np.concatenate(crossover_points[:, 1:])],
))
# 变异
mutation_mask = np.random.rand(population_size, 2) < mutation_rate
population += mutation_mask * np.random.normal(scale=0.1, size=(population_size, 2))
# 输出每代的最优解
best_solution = population[np.argmin(fitness)]
print(f"Generation {generation+1}: Best Solution - {best_solution}, Fitness - {objective_function(*best_solution)}")
# 运行遗传算法
genetic_algorithm(population_size=50, num_generations=100, crossover_rate=0.7, mutation_rate=0.1)
这个简单的示例中,我们使用遗传算法搜索函数 \(f(x, y) = x^2 + y^2\) 的最小值。遗传算法的参数包括种群大小、迭代次数、交叉率和变异率。在每一代,我们计算适应度、进行选择、交叉和变异操作,然后输出每代的最优解。在实际问题中,你需要根据问题的性质调整算法参数和适应度函数。
转载请注明出处:http://www.zyzy.cn/article/detail/12056/AI人工智能