【0-1背包问题】遗传算法 python 完整代码可直接运行

本文介绍了一种使用遗传算法求解0-1背包问题的Python实现,包括导入所需库、初始化、计算适应度、选择、交叉和变异操作。尽管存在不收敛的情况,但整体上仍能找到最优解。附带了可运行的完整代码。
摘要由CSDN通过智能技术生成

1.导入所需要的库

import numpy as np
import matplotlib.pyplot as plt

2.初始化

#初始化种群,popsize代表种群个数,n代表基因长度,
def init(popsize,n):
    population=[]
    for i in range(popsize):
        pop=''
        for j in range(n):

            pop=pop+str(np.random.randint(0,2))
        population.append(pop)
    return population

3.计算fitness

#计算种群中重量和效益
def computeFitness(population,weight,profit):
    total_weight = []
    total_profit = []
    for pop in population:
        weight_temp = 0
        profit_temp = 0
        for index in range(len(pop)):
            if pop[index] == '1':
                weight_temp += int(weight[index])
                profit_temp += int(profit[index])
        total_weight.append(weight_temp)
        total_profit.append(profit_temp)
    return  total_weight,total_profit
#计算单个个体
def computesingle(single,profit):
    profit_temp = 0
    for index in range(len(single)):
        if single[index] == '1':
            profit_temp += int(profit[index])
    return profit_temp

4.筛选

#筛选符合条件的
def select(population,weight_limit,total_weight,total_profit):
    w_temp = []
    p_temp = []
    pop_temp = []
    for weight in total_weight:
        out = total_weight.index(weight)
        if weight <= weight_limit:
            w_temp.append(total_weight[out])
            p_temp.append(total_profit[out])
            pop_temp.append(population[out])
    return pop_temp,w_temp,p_temp

4.轮盘赌选择

def roulettewheel(s_pop,total_profit):

    p =[0]
    temp = 0

    sum_profit = sum(total_profit)
    for i in range(len(total_profit)):

        unit = total_profit[i]/sum_profit
        p.append(temp+unit)
        temp += unit
    new_population = []
    i0 = 0
    while i0 < popsize:
        select_p = np.random.uniform()
        for i in range(len(s_pop)):

            if select_p 
  • 1
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
遗传算法可以用于求解纳什均衡点,以下是一个简单的Python代码示例: ```python import random # 设置博弈的参数 num_players = 2 num_strategies = 3 max_iterations = 100 population_size = 50 mutation_rate = 0.1 crossover_rate = 0.5 # 定义博弈矩阵 game_matrix = [[(1, 1), (-1, 2)], [(2, -1), (0, 0)], [(0, 0), (-1, -1)]] # 定义个体编码方式 def encode_strategy(strategy): return ''.join(str(s) for s in strategy) def decode_strategy(encoded_strategy): return [int(s) for s in encoded_strategy] # 定义适应度函数 def fitness_function(strategy): total_payoff = [0] * num_players for i in range(num_players): player_strategy = decode_strategy(strategy[i]) for j in range(num_strategies): opponent_strategy = decode_strategy(strategy[(i + 1) % num_players]) payoff = game_matrix[player_strategy][opponent_strategy][i] total_payoff[i] += payoff return sum(total_payoff) # 定义选择函数 def selection(population): fitness_scores = [fitness_function(strategy) for strategy in population] total_fitness = sum(fitness_scores) probabilities = [fitness / total_fitness for fitness in fitness_scores] selected_indices = random.choices(range(population_size), weights=probabilities, k=population_size) return [population[i] for i in selected_indices] # 定义交叉函数 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(child): mutated_child = '' for bit in child: if random.random() < mutation_rate: mutated_child += '0' if bit == '1' else '1' else: mutated_child += bit return mutated_child # 初始化种群 population = [''.join(str(random.randint(0, 1)) for _ in range(num_strategies)) for _ in range(population_size)] # 迭代 for iteration in range(max_iterations): # 选择 selected_population = selection(population) # 交叉 children = [] for i in range(0, population_size, 2): child1, child2 = crossover(selected_population[i], selected_population[i+1]) children.append(mutation(child1)) children.append(mutation(child2)) # 替换 population = children # 输出结果 fitness_scores = [fitness_function(strategy) for strategy in population] best_strategy_index = fitness_scores.index(max(fitness_scores)) best_strategy = decode_strategy(population[best_strategy_index]) print('Best strategy:', best_strategy) ``` 上述代码中,我们定义了一个2人3策略的博弈矩阵,然后使用遗传算法求解纳什均衡点。在适应度函数中,我们计算了每个个体的总收益,并以此作为适应度的度量。在选择函数中,我们使用轮盘赌选择法选择下一代种群。在交叉函数中,我们使用单点交叉法进行交叉操作。在变异函数中,我们使用随机位翻转法进行变异操作。最后,我们输出了得到的最优策略。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值