Deap : 遗传算法算法解决 背包问题
生活随笔
收集整理的這篇文章主要介紹了
Deap : 遗传算法算法解决 背包问题
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
特殊
自定義評(píng)價(jià)函數(shù)
同前
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,自定義交叉函數(shù)
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中的位運(yùn)算符
建議在新標(biāo)簽頁打開圖片
自定義變異函
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此處與之前的文章效果類似
- 粒子群優(yōu)化算法
- 短版本可以參考官網(wǎng)介紹
源代碼
#!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 # 基因編碼位數(shù) 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("最佳裝包為(最佳個(gè)體) :",hof[-1])print(len(pop))print(len(hof))print("最佳裝包時(shí)的重量與價(jià)值(最佳適應(yīng)度) :",evalKnapsack(hof[-1])) 《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的Deap : 遗传算法算法解决 背包问题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Deap: python中的遗传算法工具
- 下一篇: deap实战_2017中国数学建模大赛_