multi.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. >>>
  13. >>> # binary solution import
  14. >>> from macop.solutions.discrete import BinarySolution
  15. >>>
  16. >>> # evaluators imports
  17. >>> from macop.evaluators.discrete.mono import KnapsackEvaluator
  18. >>> from macop.evaluators.discrete.multi import WeightedSum
  19. >>> solution_data = [1, 0, 0, 1, 1, 0, 1, 0]
  20. >>> size = len(solution_data)
  21. >>> solution = BinarySolution(solution_data, size)
  22. >>>
  23. >>> # evaluator 1 initialization (worths objects passed into data)
  24. >>> worths1 = [ random.randint(5, 20) for i in range(size) ]
  25. >>> evaluator1 = KnapsackEvaluator(data={'worths': worths1})
  26. >>>
  27. >>> # evaluator 2 initialization (worths objects passed into data)
  28. >>> worths2 = [ random.randint(10, 15) for i in range(size) ]
  29. >>> evaluator2 = KnapsackEvaluator(data={'worths': worths2})
  30. >>> weighted_evaluator = WeightedSum(data={'evaluators': [evaluator1, evaluator2], 'weights': [0.3, 0.7]})
  31. >>>
  32. >>> # compute score and check with expected one
  33. >>> weighted_score = weighted_evaluator.compute(solution)
  34. >>> expected_score = evaluator1.compute(solution) * 0.3 + evaluator2.compute(solution) * 0.7
  35. >>> weighted_score == expected_score
  36. True
  37. >>> weighted_score
  38. 50.8
  39. """
  40. def compute(self, solution):
  41. """Apply the computation of fitness from solution
  42. - Associate tuple of fitness scores for each objective to the current solution
  43. - Compute weighted-sum for these objectives
  44. Args:
  45. solution: {Solution} -- Solution instance
  46. Returns:
  47. {float} -- weighted-sum of the fitness scores
  48. """
  49. scores = [
  50. evaluator.compute(solution)
  51. for evaluator in self._data['evaluators']
  52. ]
  53. # associate objectives scores to solution
  54. solution.scores = scores
  55. return sum(
  56. [scores[i] * w for i, w in enumerate(self._data['weights'])])