Deap : 遗传算法算法解决 背包问题
特殊
自定义评价函数
同前
def evalKnapsack(individual):weight = 0.0value = 0.0for item in individual:weight += items[item][0]value += items[item][1]if len(individual) > MAX_ITEM or weight > MAX_WEIGHT:return 10000, 0 # Ensure overweighted bags are dominatedreturn weight, value,
自定义交叉函数
def cxSet(ind1, ind2):"""Apply a crossover operation on input sets. The first child is theintersection of the two sets, the second child is the difference of thetwo sets."""temp = set(ind1) # Used in order to keep typeind1 &= ind2 # Intersection (inplace)ind2 ^= temp # Symmetric Difference (inplace)return ind1, ind2
&=,^= python中的位运算符
建议在新标签页打开图片
自定义变异函
def mutSet(individual):"""Mutation that pops or add an element."""if random.random() < 0.5:if len(individual) > 0: # We cannot pop from an empty setindividual.remove(random.choice(sorted(tuple(individual))))else:individual.add(random.randrange(NBR_ITEMS))return individual,
使用短版本的遗传算法
def main():random.seed(64)NGEN = 50MU = 50LAMBDA = 100CXPB = 0.7MUTPB = 0.2pop = toolbox.population(n=MU)hof = tools.ParetoFront()stats = tools.Statistics(lambda ind: ind.fitness.values)stats.register("avg", numpy.mean, axis=0)stats.register("std", numpy.std, axis=0)stats.register("min", numpy.min, axis=0)stats.register("max", numpy.max, axis=0)algorithms.eaMuPlusLambda(pop, toolbox, MU, LAMBDA, CXPB, MUTPB, NGEN, stats,halloffame=hof)return pop, stats, hof
此处与之前的文章效果类似
- 粒子群优化算法
- 短版本可以参考官网介绍
源代码
#!usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:fonttian
@file: knapsackProblem.py
@time: 2017/10/15
"""
# This file is part of DEAP.
#
# DEAP is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# DEAP is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with DEAP. If not, see <http://www.gnu.org/licenses/>.import randomimport numpyfrom deap import algorithms
from deap import base
from deap import creator
from deap import toolsIND_INIT_SIZE = 5 # 基因编码位数
MAX_ITEM = 50
MAX_WEIGHT = 50
NBR_ITEMS = 20# To assure reproductibility, the RNG seed is set prior to the items
# dict initialization. It is also seeded in main().
random.seed(64)# Create the item dictionary: item name is an integer, and value is
# a (weight, value) 2-uple.
items = {}
# Create random items and store them in the items' dictionary.
for i in range(NBR_ITEMS):items[i] = (random.randint(1, 10), random.uniform(0, 100))creator.create("Fitness", base.Fitness, weights=(-1.0, 1.0))
creator.create("Individual", set, fitness=creator.Fitness)toolbox = base.Toolbox()# Attribute generator
toolbox.register("attr_item", random.randrange, NBR_ITEMS)# Structure initializers
toolbox.register("individual", tools.initRepeat, creator.Individual,toolbox.attr_item, IND_INIT_SIZE)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)def evalKnapsack(individual):weight = 0.0value = 0.0for item in individual:weight += items[item][0]value += items[item][1]if len(individual) > MAX_ITEM or weight > MAX_WEIGHT:return 10000, 0 # Ensure overweighted bags are dominatedreturn weight, value,def cxSet(ind1, ind2):"""Apply a crossover operation on input sets. The first child is theintersection of the two sets, the second child is the difference of thetwo sets."""temp = set(ind1) # Used in order to keep typeind1 &= ind2 # Intersection (inplace)ind2 ^= temp # Symmetric Difference (inplace)return ind1, ind2def mutSet(individual):"""Mutation that pops or add an element."""if random.random() < 0.5:if len(individual) > 0: # We cannot pop from an empty setindividual.remove(random.choice(sorted(tuple(individual))))else:individual.add(random.randrange(NBR_ITEMS))return individual,toolbox.register("evaluate", evalKnapsack)
toolbox.register("mate", cxSet)
toolbox.register("mutate", mutSet)
toolbox.register("select", tools.selNSGA2)def main():random.seed(64)NGEN = 50MU = 50LAMBDA = 100CXPB = 0.7MUTPB = 0.2pop = toolbox.population(n=MU)hof = tools.ParetoFront()stats = tools.Statistics(lambda ind: ind.fitness.values)stats.register("avg", numpy.mean, axis=0)stats.register("std", numpy.std, axis=0)stats.register("min", numpy.min, axis=0)stats.register("max", numpy.max, axis=0)algorithms.eaMuPlusLambda(pop, toolbox, MU, LAMBDA, CXPB, MUTPB, NGEN, stats,halloffame=hof)return pop, stats, hofif __name__ == "__main__":pop, stats, hof = main()print("最佳装包为(最佳个体) :",hof[-1])print(len(pop))print(len(hof))print("最佳装包时的重量与价值(最佳适应度) :",evalKnapsack(hof[-1]))
Deap : 遗传算法算法解决 背包问题相关推荐
- 部分背包的贪婪算法 java_使用JAVA实现算法——贪心算法解决背包问题
packageBasePart;importjava.io.BufferedReader;importjava.io.FileInputStream;importjava.io.IOException ...
- 背包问题 贪心算法 java_JS基于贪心算法解决背包问题
前面我们分享了关于js使用贪心算法解决找零问题,本文我们接着为大家介绍JS基于贪心算法解决背包问题. 贪心算法:在对问题求解时,总是做出在当前看来是最好的选择.也就是说,不从整体最优上加以考虑,他所做 ...
- 使用ga算法解决背包问题_我如何使用算法解决现实生活中的手提背包的背包问题
使用ga算法解决背包问题 I'm a nomad and live out of one carry-on bag. This means that the total weight of all m ...
- 贪心算法解决背包问题
贪心算法解决背包问题 问题描述: 给定 n 个物品和一个容量为 C 的背包,请给出物品装入背包的方案,使得背包中物品的总价值 M 最大,并满足: 1.每个物品 I 的重量为 wi,价值为 vi. 2. ...
- 背包问题 贪心算法 java_JS基于贪心算法解决背包问题示例
本文实例讲述了JS基于贪心算法解决背包问题.分享给大家供大家参考,具体如下: 贪心算法:在对问题求解时,总是做出在当前看来是最好的选择.也就是说,不从整体最优上加以考虑,他所做出的仅是在某种意义上的局 ...
- 动态规划算法解决背包问题
一.动态规划算法概述 动态规划算法与分治法类似,其基本思想也是将待求解问题分解成若干个子问题,先求解子问题,然后从子问题解得到原问题解. 但是经分解得到的子问题往往不是互相独立的.不同子问题的数目常常 ...
- java 动态规划视频_157-动态规划算法解决背包问题1
2.网上数据结构和算法的课程不少,但存在两个问题: 1)授课方式单一,大多是照着代码念一遍,数据结构和算法本身就比较难理解,对基础好的学员来说,还好一点,对基础不好的学生来说,基本上就是听天书了 2) ...
- 用贪心算法解背包问题(装载问题)
题目描述 给定一个最大载重量为M的卡车和N种食品,有食盐,白糖,大米等.已知第 i 种食品的最多拥有Wi 公斤,其商品价值为Vi元/公斤,编程确定一个装货方案,使得装入卡车中的所有物品总价值最大. 题 ...
- 子集和与一个整数相等算法_背包问题的一个变体:如何解决Java中的分区相等子集和问题...
子集和与一个整数相等算法 by Fabian Terh 由Fabian Terh Previously, I wrote about solving the Knapsack Problem (KP) ...
最新文章
- 【每日一算法】二叉搜索树结点最小距离
- node--非阻塞式I/O,单线程,异步,事件驱动
- Hadoop分布式集群搭建hadoop2.6+Ubuntu16.04
- Android中WebView的跨域漏洞分析和应用被克隆问题情景还原(免Root获取应用沙盒数据)...
- 声学漫谈之三:听觉的分辨力
- Zabbix全方位告警接入-电话/微信/短信都支持
- Windows系统带你一步一步无脑使用babel
- 天池 在线编程 三等分(模拟)
- JavaScript 模块化编程(二):AMD规范
- 荣耀A55高调上市仅仅为孤独求败?
- html5块注释,HTML 块引用标签
- 最新可使用在线音乐网站+多解析源码
- 2022年APP系统软件开发费用一览表介绍
- iOS申请真机调试证书-图文详解
- JAVASE,JAVAEE,JAVAME的区别
- Counterfit 部署教程
- 给未来程序员的15个顶级职业建议
- VPS服务-Docker搭建个人博客网站
- 邮购了正版蓝光碟《CODEnbsp;GEASS叛逆…
- 美元霸权·《看懂世界格局的第一本书·2》