手写遗传算法求解多个参数的最大值

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

# 定义要优化的函数
def fitness_function(x, y):
    return -(x**2 + y**2) + 4*x + 5*y + 10

# 初始化种群
def initialize_population(pop_size, x_lower_bound, x_upper_bound, y_lower_bound, y_upper_bound):
    return [(random.uniform(x_lower_bound, x_upper_bound), random.uniform(y_lower_bound, y_upper_bound)) for _ in range(pop_size)]

# 计算适应度
def calculate_fitness(population):
    return [fitness_function(x, y) for x, y 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 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(individual, mutation_rate, x_lower_bound, x_upper_bound, y_lower_bound, y_upper_bound):
    x, y = individual
    if random.random() < mutation_rate:
        x = random.uniform(x_lower_bound, x_upper_bound)
    if random.random() < mutation_rate:
        y = random.uniform(y_lower_bound, y_upper_bound)
    return x, y

# 遗传算法函数
def genetic_algorithm(pop_size, num_generations, num_parents, mutation_rate, x_lower_bound, x_upper_bound, y_lower_bound, y_upper_bound):
    population = initialize_population(pop_size, x_lower_bound, x_upper_bound, y_lower_bound, y_upper_bound)

    for generation in range(num_generations):
        fitness_values = calculate_fitness(population)
        parents = 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, x_lower_bound, x_upper_bound, y_lower_bound, y_upper_bound)
            child2 = mutation(child2, mutation_rate, x_lower_bound, x_upper_bound, y_lower_bound, y_upper_bound)
            new_population.extend([child1, child2])

        population = new_population

    best_individual = max(population, key=lambda ind: fitness_function(ind[0], ind[1]))
    best_fitness = fitness_function(best_individual[0], best_individual[1])

    return best_individual, best_fitness


if __name__ == "__main__":
    pop_size = 50
    num_generations = 100
    num_parents = 10
    mutation_rate = 0.1
    x_lower_bound = -10
    x_upper_bound = 10
    y_lower_bound = -10
    y_upper_bound = 10

    best_individual, best_fitness = genetic_algorithm(pop_size, num_generations, num_parents, mutation_rate, x_lower_bound, x_upper_bound, y_lower_bound, y_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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值