multi.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """Multi-objective evaluators classes
  2. """
  3. # main imports
  4. from macop.evaluators.base import Evaluator
  5. class WeightedSum(Evaluator):
  6. """Weighted-sum sub-evaluator class which enables to compute solution using specific `_data`
  7. - stores into its `_data` dictionary attritute required measures when computing a solution
  8. - `_data['evaluators']` current evaluator to use
  9. - `_data['weights']` Associated weight to use
  10. - `compute` method enables to compute and associate a tuples of scores to a given solution
  11. >>> import random
  12. >>> # binary solution import
  13. >>> from macop.solutions.discrete import BinarySolution
  14. >>> # evaluators imports
  15. >>> from macop.evaluators.discrete.mono import KnapsackEvaluator
  16. >>> from macop.evaluators.discrete.multi import WeightedSum
  17. >>> solution_data = [1, 0, 0, 1, 1, 0, 1, 0]
  18. >>> size = len(solution_data)
  19. >>> solution = BinarySolution(solution_data, size)
  20. >>> # evaluator 1 initialization (worths objects passed into data)
  21. >>> worths1 = [ random.randint(5, 20) for i in range(size) ]
  22. >>> evaluator1 = KnapsackEvaluator(data={'worths': worths1})
  23. >>> # evaluator 2 initialization (worths objects passed into data)
  24. >>> worths2 = [ random.randint(10, 15) for i in range(size) ]
  25. >>> evaluator2 = KnapsackEvaluator(data={'worths': worths2})
  26. >>> weighted_evaluator = WeightedSum(data={'evaluators': [evaluator1, evaluator2], 'weights': [0.3, 0.7]})
  27. >>> weighted_score = weighted_evaluator.compute(solution)
  28. >>> expected_score = evaluator1.compute(solution) * 0.3 + evaluator2.compute(solution) * 0.7
  29. >>> weighted_score == expected_score
  30. True
  31. >>> weighted_score
  32. 50.8
  33. """
  34. def compute(self, solution):
  35. """Apply the computation of fitness from solution
  36. - Associate tuple of fitness scores for each objective to the current solution
  37. - Compute weighted-sum for these objectives
  38. Args:
  39. solution: {Solution} -- Solution instance
  40. Returns:
  41. {float} -- weighted-sum of the fitness scores
  42. """
  43. scores = [evaluator.compute(solution) for evaluator in self._data['evaluators']]
  44. # associate objectives scores to solution
  45. solution._scores = scores
  46. return sum([scores[i] * w for i, w in enumerate(self._data['weights'])])