You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

base_metric.py 2.6 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import logging
  2. from abc import ABCMeta, abstractmethod
  3. from typing import Any, List, Optional
  4. from ...utils import print_log
  5. from ..structures import ListData
  6. class BaseMetric(metaclass=ABCMeta):
  7. """
  8. Base class for a metrics.
  9. The metrics first processes each batch of data_examples and appends the processed
  10. results to the results list. Then, it computes the metrics of the entire dataset.
  11. Parameters
  12. ----------
  13. prefix : str, optional
  14. The prefix that will be added in the metrics names to disambiguate homonymous
  15. metrics of different tasks. If prefix is not provided in the argument,
  16. self.default_prefix will be used instead. Default to None.
  17. """
  18. def __init__(
  19. self,
  20. prefix: Optional[str] = None,
  21. ) -> None:
  22. self.default_prefix = ""
  23. self.results: List[Any] = []
  24. self.prefix = prefix or self.default_prefix
  25. @abstractmethod
  26. def process(self, data_examples: ListData) -> None:
  27. """
  28. Process one batch of data examples. The processed results should be stored
  29. in ``self.results``, which will be used to compute the metrics when all
  30. batches have been processed.
  31. Parameters
  32. ----------
  33. data_examples : ListData
  34. A batch of data examples.
  35. """
  36. @abstractmethod
  37. def compute_metrics(self) -> dict:
  38. """
  39. Compute the metrics from processed results.
  40. Returns
  41. -------
  42. dict
  43. The computed metrics. The keys are the names of the metrics,
  44. and the values are corresponding results.
  45. """
  46. def evaluate(self) -> dict:
  47. """
  48. Evaluate the model performance of the whole dataset after processing
  49. all batches.
  50. Returns
  51. -------
  52. dict
  53. Evaluation metrics dict on the val dataset. The keys are the
  54. names of the metrics, and the values are corresponding results.
  55. """
  56. if len(self.results) == 0:
  57. print_log(
  58. f"{self.__class__.__name__} got empty `self.results`. Please "
  59. "ensure that the processed results are properly added into "
  60. "`self.results` in `process` method.",
  61. logger="current",
  62. level=logging.WARNING,
  63. )
  64. metrics = self.compute_metrics()
  65. # Add prefix to metrics names
  66. if self.prefix:
  67. metrics = {"/".join((self.prefix, k)): v for k, v in metrics.items()}
  68. # reset the results list
  69. self.results.clear()
  70. return metrics

An efficient Python toolkit for Abductive Learning (ABL), a novel paradigm that integrates machine learning and logical reasoning in a unified framework.