knapsackExample.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # main imports
  2. import logging
  3. import os
  4. import random
  5. # module imports
  6. from macop.solutions.discrete import BinarySolution
  7. from macop.evaluators.discrete.mono import KnapsackEvaluator
  8. from macop.operators.discrete.mutators import SimpleMutation
  9. from macop.operators.discrete.mutators import SimpleBinaryMutation
  10. from macop.operators.discrete.crossovers import SimpleCrossover
  11. from macop.operators.discrete.crossovers import RandomSplitCrossover
  12. from macop.policies.classicals import RandomPolicy
  13. from macop.policies.reinforcement import UCBPolicy
  14. from macop.algorithms.mono import IteratedLocalSearch as ILS
  15. from macop.callbacks.classicals import BasicCheckpoint
  16. if not os.path.exists('data'):
  17. os.makedirs('data')
  18. # logging configuration
  19. logging.basicConfig(format='%(asctime)s %(message)s', filename='data/example.log', level=logging.DEBUG)
  20. random.seed(42)
  21. elements_score = [ random.randint(1, 20) for _ in range(30) ]
  22. elements_weight = [ random.randint(2, 5) for _ in range(30) ]
  23. def knapsackWeight(solution):
  24. weight_sum = 0
  25. for index, elem in enumerate(solution._data):
  26. weight_sum += elements_weight[index] * elem
  27. return weight_sum
  28. # default validator
  29. def validator(solution):
  30. if knapsackWeight(solution) <= 80:
  31. return True
  32. else:
  33. False
  34. # define init random solution
  35. def init():
  36. return BinarySolution.random(30, validator)
  37. filepath = "data/checkpoints.csv"
  38. def main():
  39. operators = [SimpleBinaryMutation(), SimpleMutation(), SimpleCrossover(), RandomSplitCrossover()]
  40. policy = UCBPolicy(operators)
  41. callback = BasicCheckpoint(every=5, filepath=filepath)
  42. evaluator = KnapsackEvaluator(data={'worths': elements_score})
  43. algo = ILS(init, evaluator, operators, policy, validator, maximise=True, verbose=False)
  44. # add callback into callback list
  45. algo.addCallback(callback)
  46. bestSol = algo.run(1000)
  47. print('Solution score is {}'.format(evaluator.compute(bestSol)))
  48. print('Solution weigth is {}'.format(knapsackWeight(bestSol)))
  49. if __name__ == "__main__":
  50. main()