手推遗传算法,寻找最大值(单目标函数和多目标函数)

单目标函数

# 通过遗传算法求解单个参数的最大值
import random


# 定义适应度函数
def fitness_function(x):
    return x ** 2 - 4 * x + 4


# 初始化总群
def initialize_population(pop_size, lower_bound, upper_bound):
    return [random.uniform(lower_bound, upper_bound) for _ in range(pop_size)]


# 计算每个总群的适应度
def calculate_fitness(population):
    return [fitness_function(individual) for individual in population]


# 选择:根据他们的适应度选择最佳种群
def selection(population, fitness_values, num_parents):
    sorted_population = [x for _, x in sorted(zip(fitness_values, population), reverse=True)]
    return sorted_population[:num_parents]


# 突变:引入随机突变以保持多样性
def mutation(individual, mutation_rate, lower_bound, upper_bound):
    if random.random() < mutation_rate:
        return random.uniform(lower_bound, upper_bound)
    return individual


# 遗传算法函数
def genetic_algorithm(pop_size, num_generations, num_parents, mutation_rate, lower_bound, upper_bound):
    population = initialize_population(pop_size, lower_bound, upper_bound)

    for generation in range(num_generations):
        fitness_values = calculate_fitness(population)
        parents = selection(population, fitness_values, num_parents)

        new_population = []

        for parent in parents:
            child = mutation(parent, mutation_rate, lower_bound, upper_bound)
            new_population.append(child)

        population = new_population

    best_individual = max(population, key=fitness_function)
    best_fitness = fitness_function(best_individual)

    return best_individual, best_fitness


if __name__ == "__main__":
    pop_size = 50
    num_generations = 100
    num_parents = 20
    mutation_rate = 0.1
    lower_bound = -10
    upper_bound = 10

    best_individual, best_fitness = genetic_algorithm(pop_size, num_generations, num_parents, mutation_rate,
                                                      lower_bound, upper_bound)

    print("Best individual:", best_individual)
    print("Best fitness:", best_fitness)

多目标函数

import random
from random import sample

# 定义要优化的函数(假设有五个参数 x1, x2, x3, x4, x5)
def fitness_function(x1, x2, x3, x4, x5):
    return -(x1 + 2*x2 + 3*x3 + 4*x4 + 5*x5)  # 负号用于寻找最大值

# 初始化种群
def initialize_population(pop_size, lower_bound, upper_bound):
    return [[random.uniform(lower_bound, upper_bound) for _ in range(5)] for _ in range(pop_size)]

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

# 选择
def selection(population, fitness_values, num_parents):
    sorted_population = [x for _, x in sorted(zip(fitness_values, population), reverse=True)]
    return sorted_population[:num_parents]
    # return sorted_population[:num_parents], sorted_population[num_parents:]

# 交叉
def crossover(parent1, parent2):
    crossover_point = random.randint(1, 4)
    child1 = parent1[:crossover_point] + parent2[crossover_point:]
    child2 = parent2[:crossover_point] + parent1[crossover_point:]
    return child1, child2

# 变异
def mutation(individual, mutation_rate, lower_bound, upper_bound):
    for i in range(5):
        if random.random() < mutation_rate:
            individual[i] = random.uniform(lower_bound, upper_bound)
    return individual

# 遗传算法函数
def genetic_algorithm(pop_size, num_generations, num_parents, mutation_rate, lower_bound, upper_bound):
    population = initialize_population(pop_size, lower_bound, upper_bound)

    for generation in range(num_generations):
        fitness_values = calculate_fitness(population)
        parents = selection(population, fitness_values, num_parents)
        # parents, rest = selection(population, fitness_values, num_parents)
        new_population = []

        for i in range(0, len(parents), 2):
            parent1, parent2 = parents[i], parents[i+1]
            child1, child2 = crossover(parent1, parent2)
            child1 = mutation(child1, mutation_rate, lower_bound, upper_bound)
            child2 = mutation(child2, mutation_rate, lower_bound, upper_bound)
            new_population.extend([child1, child2])

        # population = new_population + rest
        population = new_population + sample(population, pop_size-num_parents)

        # while len(new_population) < pop_size:  # Keep generating children until reaching the desired pop_size
        #     parent1, parent2 = random.sample(parents, 2)
        #     child1, child2 = crossover(parent1, parent2)
        #     child1 = mutation(child1, mutation_rate, lower_bound, upper_bound)
        #     child2 = mutation(child2, mutation_rate, lower_bound, upper_bound)
        #     new_population.extend([child1, child2])
        #
        # population = new_population[:pop_size]  # Truncate if new_population exceeds pop_size

    best_individual = max(population, key=lambda ind: fitness_function(*ind))
    best_fitness = fitness_function(*best_individual)

    return best_individual, best_fitness

if __name__ == "__main__":
    pop_size = 50
    num_generations = 100
    num_parents = 10
    mutation_rate = 0.1
    lower_bound = -10
    upper_bound = 10

    best_individual, best_fitness = genetic_algorithm(pop_size, num_generations, num_parents, mutation_rate, lower_bound, upper_bound)

    print("Best individual:", best_individual)
    print("Best fitness:", best_fitness)
  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值