遗传算法最值问题python代码
时间: 2023-11-04 20:58:29 浏览: 56
遗传算法是一种优化算法,用于解决最值问题。下面是一个简单的遗传算法的 Python 代码示例,用于求解一个目标函数的最大值。
```python
import random
# 目标函数
def objective_function(x):
return -x**2 + 4
# 初始化种群
def initialize_population(population_size, num_variables):
population = []
for _ in range(population_size):
chromosome = [random.randint(0, 1) for _ in range(num_variables)]
population.append(chromosome)
return population
# 计算适应度
def fitness(chromosome):
x = decode_chromosome(chromosome)
return objective_function(x)
# 解码染色体得到实际数值
def decode_chromosome(chromosome):
x = 0
for i in range(len(chromosome)):
x += chromosome[i] * (2**i)
return x
# 交叉操作
def crossover(parent1, parent2):
crossover_point = random.randint(1, len(parent1)-1)
child1 = parent1[:crossover_point] + parent2[crossover_point:]
child2 = parent2[:crossover_point] + parent1[crossover_point:]
return child1, child2
# 变异操作
def mutation(chromosome, mutation_rate):
mutated_chromosome = []
for gene in chromosome:
if random.random() < mutation_rate:
mutated_gene = 1 - gene
else:
mutated_gene = gene
mutated_chromosome.append(mutated_gene)
return mutated_chromosome
# 遗传算法主函数
def genetic_algorithm(population_size, num_variables, num_generations):
population = initialize_population(population_size, num_variables)
for _ in range(num_generations):
# 计算适应度
fitness_values = [fitness(chromosome) for chromosome in population]
# 选择操作
selected_indices = random.choices(range(population_size), weights=fitness_values, k=2)
parent1 = population[selected_indices[0]]
parent2 = population[selected_indices[1]]
# 交叉操作
child1, child2 = crossover(parent1, parent2)
# 变异操作
child1 = mutation(child1, mutation_rate=0.01)
child2 = mutation(child2, mutation_rate=0.01)
# 更新种群
population[selected_indices[0]] = child1
population[selected_indices[1]] = child2
# 找到最优解
best_chromosome = max(population, key=fitness)
best_solution = decode_chromosome(best_chromosome)
best_fitness = fitness(best_chromosome)
return best_solution, best_fitness
# 示例运行
best_solution, best_fitness = genetic_algorithm(population_size=100, num_variables=4, num_generations=50)
print("最优解:", best_solution)
print("最优解的适应度:", best_fitness)
```