knapsackMultiExample.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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.multi import MOEAD
  15. from macop.callbacks.multi import MultiCheckpoint
  16. from macop.callbacks.multi import ParetoCheckpoint
  17. from macop.callbacks.policies import UCBCheckpoint
  18. if not os.path.exists('data'):
  19. os.makedirs('data')
  20. # logging configuration
  21. logging.basicConfig(format='%(asctime)s %(message)s', filename='data/exampleMOEAD.log', level=logging.DEBUG)
  22. random.seed(42)
  23. elements_score1 = [ random.randint(1, 100) for _ in range(500) ]
  24. elements_score2 = [ random.randint(1, 200) for _ in range(500) ]
  25. elements_weight = [ random.randint(90, 100) for _ in range(500) ]
  26. def knapsackWeight(solution):
  27. weight_sum = 0
  28. for index, elem in enumerate(solution._data):
  29. weight_sum += elements_weight[index] * elem
  30. return weight_sum
  31. # default validator
  32. def validator(solution):
  33. if knapsackWeight(solution) <= 15000:
  34. return True
  35. else:
  36. False
  37. # define init random solution
  38. def init():
  39. return BinarySolution.random(200, validator)
  40. mo_checkpoint_path = "data/checkpointsMOEAD.csv"
  41. pf_checkpoint_path = "data/pfMOEAD.csv"
  42. ucb_checkpoint_path = "data/UCBPolicyMOEAD.csv"
  43. def main():
  44. operators = [SimpleBinaryMutation(), SimpleMutation(), SimpleCrossover(), RandomSplitCrossover()]
  45. policy = UCBPolicy(operators, C=100, exp_rate=0.2)
  46. evaluator1 = KnapsackEvaluator(data={'worths': elements_score1})
  47. evaluator2 = KnapsackEvaluator(data={'worths': elements_score2})
  48. # pass list of evaluators
  49. algo = MOEAD(20, 5, init, [evaluator1, evaluator2], operators, policy, validator, maximise=True)
  50. algo.addCallback(MultiCheckpoint(every=5, filepath=mo_checkpoint_path))
  51. algo.addCallback(ParetoCheckpoint(every=5, filepath=pf_checkpoint_path))
  52. algo.addCallback(UCBCheckpoint(every=5, filepath=ucb_checkpoint_path))
  53. paretoFront = algo.run(1000)
  54. print("Pareto front is composed of", len(paretoFront), "solutions")
  55. if __name__ == "__main__":
  56. main()