knapsackExample.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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.algorithms.mono import HillClimberFirstImprovment
  16. from macop.callbacks.classicals import BasicCheckpoint
  17. if not os.path.exists('data'):
  18. os.makedirs('data')
  19. # logging configuration
  20. logging.basicConfig(format='%(asctime)s %(message)s', filename='data/example_knapsack.log', level=logging.DEBUG)
  21. random.seed(42)
  22. elements_score = [ random.randint(1, 20) for _ in range(30) ]
  23. elements_weight = [ random.randint(2, 5) for _ in range(30) ]
  24. def knapsackWeight(solution):
  25. weight_sum = 0
  26. for index, elem in enumerate(solution.data):
  27. weight_sum += elements_weight[index] * elem
  28. return weight_sum
  29. # default validator
  30. def validator(solution):
  31. if knapsackWeight(solution) <= 80:
  32. return True
  33. else:
  34. False
  35. # define init random solution
  36. def init():
  37. return BinarySolution.random(30, validator)
  38. filepath = "data/checkpoints.csv"
  39. def main():
  40. operators = [SimpleBinaryMutation(), SimpleMutation(), SimpleCrossover(), RandomSplitCrossover()]
  41. policy = UCBPolicy(operators)
  42. callback = BasicCheckpoint(every=5, filepath=filepath)
  43. evaluator = KnapsackEvaluator(data={'worths': elements_score})
  44. # passing global evaluation param from ILS
  45. hcfi = HillClimberFirstImprovment(init, evaluator, operators, policy, validator, maximise=True, verbose=False)
  46. algo = ILS(init, evaluator, operators, policy, validator, localSearch=hcfi, maximise=True, verbose=False)
  47. # add callback into callback list
  48. algo.addCallback(callback)
  49. bestSol = algo.run(1000)
  50. print('Solution score is {}'.format(evaluator.compute(bestSol)))
  51. print('Solution weigth is {}'.format(knapsackWeight(bestSol)))
  52. if __name__ == "__main__":
  53. main()