遗传算法python实现

期望的搜索精度:   0.01

二进制串的长度l:  10

种群规模:         10

pc:                 0.9

pm:                0.05

适应度评价次数:   1000

赌轮选择、一点交叉、精英保存

个体适应度=目标函数值

import numpy as np


# 定义目标函数
def fitness_function(x):
    return -x ** 2 + 10 * np.cos(2 * np.pi * x) + 30

# 赌轮选择(适应度比例选择)
def roulette_wheel_selection(fitness_scores):
    total_fitness = sum(fitness_scores)
    selection_probs = [fitness / total_fitness for fitness in fitness_scores]
    cum_probs = np.cumsum(selection_probs)
    selected_indices = []
    for _ in range(len(fitness_scores)):
        r = np.random.rand()
        for i, cp in enumerate(cum_probs):
            if r <= cp:
                selected_indices.append(i)
                break
    return np.array(selected_indices)

# 一点交叉
def crossover_one_point(parent1, parent2, crossover_rate):
    if np.random.rand() < crossover_rate:
        crosspoint = np.random.randint(1, len(parent1) - 1)
        child1 = np.concatenate((parent1[:crosspoint], parent2[crosspoint:]))
        child2 = np.concatenate((parent2[:crosspoint], parent1[crosspoint:]))
        return child1, child2
    else:
        # 如果不发生交叉,则直接复制父代
        return parent1.copy(), parent2.copy()

# 精英保存
def elitism_save(population, selected_indices, num_elites):
    sorted_indices = np.argsort(-np.array(calculate_fitness(population)))[:num_elites]
    elite_population = [population[idx] for idx in sorted_indices]
    return elite_population

# 初始化种群
def initialize_population(population_size, chromosome_length):
    lower_bound, upper_bound = -5, 5
    return (upper_bound - lower_bound) * np.random.rand(population_size, chromosome_length) + lower_bound

# 计算种群适应度
def calculate_fitness(population):
    return [fitness_function(individual[0]) for individual in population]

# 遗传算法主流程
def genetic_algorithm(pc, pm, expected_accuracy, max_iterations):
    population_size = 10
    chromosome_length = 10

    # 初始化种群
    population = initialize_population(population_size, chromosome_length)

    # 主循环
    for _ in range(max_iterations):
        # 计算适应度
        fitness_scores = calculate_fitness(population)

        # 赌轮选择
        selected_indices = roulette_wheel_selection(fitness_scores)

        # 精英保存
        elite_population = elitism_save(population, selected_indices, 1)

        # 一点交叉生成新种群
        new_population = []
        while len(new_population) < population_size:
            parent1_index, parent2_index = selected_indices[np.random.choice(len(selected_indices), 2, replace=False)]
            child1, child2 = crossover_one_point(population[parent1_index], population[parent2_index], pm)
            new_population.extend([child1, child2])

        # 变异
        for i in range(population_size):
            if np.random.rand() < pc:
                new_population[i] += (np.random.rand(chromosome_length) - 0.5) * 2 * expected_accuracy

        # 规范化到解空间
        new_population = np.clip(new_population, -5, 5)

        # 添加精英个体
        new_population[:len(elite_population)] = elite_population

        # 更新种群
        population = new_population

    # 返回最优解
    best_individual_index = np.argmax(calculate_fitness(population))
    return population[best_individual_index], calculate_fitness(population)[best_individual_index]

if __name__ == '__main__':
    # 运行遗传算法
    for i in range(10):
        best_solution, best_fitness = genetic_algorithm(0.9, 0.05, 0.01, 1000)
        print(f"最优解: {best_solution}\n适应度: {best_fitness}\n")

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值