以下是一个简单的遗传算法的 Python 代码,用于求解目标函数 f(x) = x^2 的最小值:

import random

# 定义目标函数,这里以求解 f(x) = x^2 的最小值为例
def objective_function(x):
    return x**2

# 定义遗传算法参数
population_size = 10 # 种群大小
chromosome_length = 5 # 染色体长度
mutation_rate = 0.1 # 变异率
crossover_rate = 0.8 # 交叉率
max_generation = 100 # 最大迭代次数

# 初始化种群
def init_population(population_size, chromosome_length):
    population = []
    for i in range(population_size):
        chromosome = []
        for j in range(chromosome_length):
            chromosome.append(random.randint(0, 1))
        population.append(chromosome)
    return population

# 计算适应度
def calculate_fitness(chromosome):
    x = 0
    for i in range(len(chromosome)):
        x += chromosome[i] * (2 ** i)
    return objective_function(x)

# 选择
def selection(population):
    fitness_values = [calculate_fitness(chromosome) for chromosome in population]
    total_fitness = sum(fitness_values)
    probabilities = [fitness / total_fitness for fitness in fitness_values]
    cumulative_probabilities = [sum(probabilities[:i+1]) for i in range(len(probabilities))]
    new_population = []
    for i in range(len(population)):
        r = random.random()
        for j in range(len(cumulative_probabilities)):
            if r <= cumulative_probabilities[j]:
                new_population.append(population[j])
                break
    return new_population

# 交叉
def crossover(parent1, parent2):
    if random.random() < crossover_rate:
        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
    else:
        return parent1, parent2

# 变异
def mutation(chromosome):
    for i in range(len(chromosome)):
        if random.random() < mutation_rate:
            chromosome[i] = 1 - chromosome[i]
    return chromosome

# 遗传算法主函数
def genetic_algorithm(population_size, chromosome_length, mutation_rate, crossover_rate, max_generation):
    population = init_population(population_size, chromosome_length)
    for i in range(max_generation):
        population = selection(population)
        new_population = []
        for j in range(int(population_size/2)):
            parent1 = population[random.randint(0, population_size-1)]
            parent2 = population[random.randint(0, population_size-1)]
            child1, child2 = crossover(parent1, parent2)
            child1 = mutation(child1)
            child2 = mutation(child2)
            new_population.append(child1)
            new_population.append(child2)
        population = new_population
    best_chromosome = max(population, key=calculate_fitness)
    x = 0
    for i in range(len(best_chromosome)):
        x += best_chromosome[i] * (2 ** i)
    return x, objective_function(x)

# 测试
best_x, best_y = genetic_algorithm(population_size, chromosome_length, mutation_rate, crossover_rate, max_generation)
print('最优解:x =', best_x, 'y =', best_y)

该代码实现了一个简单的遗传算法,用于求解目标函数 f(x) = x^2 的最小值。其中,init_population() 函数用于初始化种群,calculate_fitness() 函数用于计算适应度,selection() 函数用于选择,crossover() 函数用于交叉,mutation() 函数用于变异,genetic_algorithm() 函数是遗传算法的主函数。在主函数中,首先初始化种群,然后进行若干代的选择、交叉和变异,最终得到最优解。

该代码可以作为学习遗传算法的入门示例,读者可以根据自己的需求进行修改和扩展。

Python 遗传算法代码示例 - 求解最小值

原文地址: https://www.cveoy.top/t/topic/jkT2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录