I am currently working in an implementation of the knapsack problem in python using the libray DEAP. I have to maximize the benefit and minimize the preference. The problem cannot have more elements inside the knapsak than a selected number.
I have generated the following function:
def evaluate(individual):
weight = sum(individual[i] * weights[i] for i in range(len(individual)))
benefit = sum(individual[i] * benefits[i] for i in range(len(individual)))
preference = sum(individual[i] * preferences[i] for i in range(len(individual)))
nTotal=sum(individual)
if weight > max_weight:
return -benefit + (weight - max_weight)*10000, preference+10
elif nTotal > nMax:
return -benefit + (nTotal - nMax)*10000, preference+10
else:
return -benefit, preference
alongside
creator.create("FitnessMulti", base.Fitness, weights=(1.0, 1.0))
creator.create("Individual", list, fitness=creator.FitnessMulti)
toolbox = base.Toolbox()
toolbox.register("attr_bool", random.randint, 0, 1)
toolbox.register("individual", generate_individual)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
toolbox.register("evaluate", evaluate)
toolbox.register("mate", tools.cxTwoPoint)
toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
toolbox.register("select", tools.selNSGA2)
My solutions do not respect the restriction in weight nor the restriction in the number of elements.
Can someone please help me to define a better version of evaluate so that I can enforce the restrictions?
If someone is interested, I can post the whole code