遗传算法解决背包问题(python)

01背包问题

1.问题重述

给定n个物品,价值分别是:v1,v2,…,vn,重量分别是:w1,w2,…,wn。在物品不可分割的情况下,挑选物品放入承重为W的背包,使得背包内物品的价值最大,且背包内物品的总重量小于W.

2.解决方案

本问题可用多种方法解决,这里采用遗传算法来求解,以下是遗传算法的流程图:
遗传算法流程图
要采用遗传算法,则首先确定以下几个要素:染色体的编码方法、适值函数、染色体交叉和变异采用的方案、选择策略

2.1 染色体的编码方法

基因编码的方法都有:二进制、整数编码、顺序编码、 实数编码等
对于01背包问题,由于每一个物体都有选或者不选两种情况,即可以用0、1来表示选择或是没有选择。故可使用二进制的编码方法来对染色体编码,且染色体长度为物体个数。

def initPopulation(self):
    """初始化种群"""
    self.lives = []
    for i in range(self.lifeCount):
        gene = [random.randint(0,1) for x in range(self.geneLenght)] # 初始化染色体
        life = Life(gene) # 生成个体
        self.lives.append(life) # 扩展种群
2.2 适值函数的选择

在确定适值函数时,首先要确定是求最小值优化问题还是求最大值优化问题,当求最大值优化问题时,可直接将目标函数当做适值函数,求最小值优化问题时,通过变换将其变为求最大值优化问题。
确定目标函数时,要先确定求解目标以及约束条件。此问题的目标是求一个X=(x1,x2…xn)(xi为0或1),从而使得V(总价值)最大,而约束条件则是W(背包承重)。以下为我的目标函数:

f ( x ) = ∑ i = 1 n x i ∗ v i              ∑ i = 1 n x i ∗ w i ⩽ W f(x)=\sum_{i=1}^n x_i*v_i \ \ \ \ \ \ \ \ \ \ \ \ \sum_{i=1}^n x_i*w_i\leqslant W f(x)=i=1nxivi            i=1nxiwiW f ( x ) = ∑ i = 1 n x i ∗ v i ∑ i = 1 n x i ∗ w i + 1 − W              ∑ i = 1 n x i ∗ w i > W f(x)=\frac{\sum_{i=1}^n x_i*v_i} {\sum_{i=1}^n x_i*w_i+1-W} \ \ \ \ \ \ \ \ \ \ \ \ \sum_{i=1}^n x_i*w_i>W f(x)=i=1nxiwi+1Wi=1nxivi            i=1nxiwi>W为了让物体尽可能装满背包,故又加入了罚值函数:
P ( x ) = 1 − ∣ ∑ i = 1 n x i ∗ w i − W ∣ δ P(x)=1-\frac{\lvert\sum_{i=1}^n x_i*w_i-W\rvert} δ P(x)=1δi=1nxiwiW其中
δ = m a x { W , ∣ ∑ i = 1 ∗ w i − W ∣ } δ=max\{W,\lvert\sum_{i=1}^*w_i-W\rvert\} δ=max{W,i=1wiW}从中不难看出,当总重越接近W时,p(x)越接近1。
最终,适值函数确定为:
F ( x ) = f ( x ) ∗ P ( x ) F(x)=f(x)*P(x) F(x)=f(x)P(x)代码如下:

def matchFun(self):
    """适值函数"""
    Max = max(self.allGoods, abs(sum(self.goods[i][0] for i in range(len(self.goods))) - self.allGoods))

    return lambda life: self.price(life.gene)[1]/(self.price(life.gene)[0]+1-self.allGoods)*\
                        (1-abs(self.price(life.gene)[0]-self.allGoods)/Max) \
        if self.price(life.gene)[0]>self.allGoods \
        else self.price(life.gene)[1]*(1-abs(self.price(life.gene)[0]-self.allGoods)/Max)

此函数的返回值为一个由lambda定义的函数,这样可以将它作为形参传递到其他类中调用,有点类似于C++中的函数指针。

2.3 交叉

此处采取的交叉策略是随机从其他染色体上截取一段基因,与原染色体上的此段基因片段交换,来得到新染色体

def cross(self, parent1, parent2):
    """交叉"""
    index1 = random.randint(0, self.geneLenght - 1)
    index2 = random.randint(index1, self.geneLenght - 1)
    newGene = []

    newGene.extend(parent1.gene[:index1])
    newGene.extend(parent2.gene[index1:index2])
    newGene.extend(parent1.gene[index2:])

    self.crossCount += 1
    return newGene      # 返回交叉后的parent1.gene
2.4 变异

此处采取的变异策略是随机改变染色体中一处基因的值(有一定概率此染色体会继续变异,故此处用了递归)

def mutation(self, gene):
    """突变,两个基因互换位置"""
    index1 = random.randint(0, self.geneLenght - 1)

    newGene = gene[:]       # 产生一个新的基因序列,以免变异的时候影响父种群
    newGene[index1] = (newGene[index1]+1)%2
    if random.random() < self.mutationRate:
        self.mutation(newGene)
    self.mutationCount += 1
    return newGene
3. 源码

源码见 https://github.com/cao-ge/Heuristic_Algorithm

  • 3
    点赞
  • 61
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
遗传算法是一种基于自然选择和遗传学原理的优化算法,可以用于解决背包问题。具体步骤如下: 1. 初始化种群:随机生成一定数量的个体,每个个体代表一种背包的组合方案。 2. 适应度函数:计算每个个体的适应度,即背包中物品的总价值。 3. 选择操作:根据适应度函数的值,选择一定数量的个体作为下一代的父代。 4. 交叉操作:对父代进行交叉操作,生成新的个体。 5. 变异操作:对新的个体进行变异操作,引入新的基因。 6. 重复步骤2-5,直到达到预设的终止条件。 7. 输出最优解:输出适应度函数值最大的个体,即为最优解。 下面是一个使用遗传算法解决背包问题Python代码示例: ```python import random # 背包容量 capacity = 80 # 物品列表,每个元素为元组,第一个元素为物品重量,第二个元素为物品价值 items = [(35, 10), (30, 40), (60, 30), (50, 50), (40, 35), (10, 40)] # 种群大小 pop_size = 50 # 迭代次数 max_iter = 100 # 交叉概率 crossover_prob = 0.8 # 变异概率 mutation_prob = 0.1 # 初始化种群 def init_population(): population = [] for i in range(pop_size): chromosome = [] for j in range(len(items)): chromosome.append(random.randint(0, 1)) population.append(chromosome) return population # 计算适应度函数值 def fitness(chromosome): weight = 0 value = 0 for i in range(len(chromosome)): if chromosome[i] == 1: weight += items[i][0] value += items[i][1] if weight > capacity: value = 0 return value # 选择操作 def selection(population): fitness_values = [fitness(chromosome) for chromosome in population] total_fitness = sum(fitness_values) probabilities = [fitness_value / total_fitness for fitness_value in fitness_values] selected_population = [] for i in range(pop_size): selected_chromosome = random.choices(population, probabilities)[0] selected_population.append(selected_chromosome) return selected_population # 交叉操作 def crossover(population): new_population = [] for i in range(pop_size): parent1 = population[i] if random.random() < crossover_prob: parent2 = random.choice(population) crossover_point = random.randint(1, len(items) - 1) child1 = parent1[:crossover_point] + parent2[crossover_point:] child2 = parent2[:crossover_point] + parent1[crossover_point:] new_population.append(child1) new_population.append(child2) else: new_population.append(parent1) return new_population # 变异操作 def mutation(population): for i in range(pop_size): chromosome = population[i] for j in range(len(items)): if random.random() < mutation_prob: chromosome[j] = 1 - chromosome[j] return population # 遗传算法求解背包问题 def genetic_algorithm(): population = init_population() for i in range(max_iter): population = selection(population) population = crossover(population) population = mutation(population) best_chromosome = max(population, key=fitness) best_fitness = fitness(best_chromosome) return best_chromosome, best_fitness # 输出最优解 best_chromosome, best_fitness = genetic_algorithm() print("最优解:", best_chromosome) print("最优解对应的价值:", best_fitness) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值