pr_curve.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. from __future__ import annotations
  2. import numbers
  3. from typing import TYPE_CHECKING, Iterable, TypeVar
  4. import wandb
  5. from wandb import util
  6. from wandb.plot.custom_chart import plot_table
  7. from wandb.plot.utils import test_missing, test_types
  8. if TYPE_CHECKING:
  9. from wandb.plot.custom_chart import CustomChart
  10. T = TypeVar("T")
  11. def pr_curve(
  12. y_true: Iterable[T] | None = None,
  13. y_probas: Iterable[numbers.Number] | None = None,
  14. labels: list[str] | None = None,
  15. classes_to_plot: list[T] | None = None,
  16. interp_size: int = 21,
  17. title: str = "Precision-Recall Curve",
  18. split_table: bool = False,
  19. ) -> CustomChart:
  20. """Constructs a Precision-Recall (PR) curve.
  21. The Precision-Recall curve is particularly useful for evaluating classifiers
  22. on imbalanced datasets. A high area under the PR curve signifies both high
  23. precision (a low false positive rate) and high recall (a low false negative
  24. rate). The curve provides insights into the balance between false positives
  25. and false negatives at various threshold levels, aiding in the assessment of
  26. a model's performance.
  27. Args:
  28. y_true: True binary labels. The shape should be (`num_samples`,).
  29. y_probas: Predicted scores or probabilities for each class.
  30. These can be probability estimates, confidence scores, or non-thresholded
  31. decision values. The shape should be (`num_samples`, `num_classes`).
  32. labels: Optional list of class names to replace
  33. numeric values in `y_true` for easier plot interpretation.
  34. For example, `labels = ['dog', 'cat', 'owl']` will replace 0 with
  35. 'dog', 1 with 'cat', and 2 with 'owl' in the plot. If not provided,
  36. numeric values from `y_true` will be used.
  37. classes_to_plot: Optional list of unique class values from
  38. y_true to be included in the plot. If not specified, all unique
  39. classes in y_true will be plotted.
  40. interp_size: Number of points to interpolate recall values. The
  41. recall values will be fixed to `interp_size` uniformly distributed
  42. points in the range [0, 1], and the precision will be interpolated
  43. accordingly.
  44. title: Title of the plot. Defaults to "Precision-Recall Curve".
  45. split_table: Whether the table should be split into a separate section
  46. in the W&B UI. If `True`, the table will be displayed in a section named
  47. "Custom Chart Tables". Default is `False`.
  48. Returns:
  49. CustomChart: A custom chart object that can be logged to W&B. To log the
  50. chart, pass it to `wandb.log()`.
  51. Raises:
  52. wandb.Error: If NumPy, pandas, or scikit-learn is not installed.
  53. Example:
  54. ```python
  55. import wandb
  56. # Example for spam detection (binary classification)
  57. y_true = [0, 1, 1, 0, 1] # 0 = not spam, 1 = spam
  58. y_probas = [
  59. [0.9, 0.1], # Predicted probabilities for the first sample (not spam)
  60. [0.2, 0.8], # Second sample (spam), and so on
  61. [0.1, 0.9],
  62. [0.8, 0.2],
  63. [0.3, 0.7],
  64. ]
  65. labels = ["not spam", "spam"] # Optional class names for readability
  66. with wandb.init(project="spam-detection") as run:
  67. pr_curve = wandb.plot.pr_curve(
  68. y_true=y_true,
  69. y_probas=y_probas,
  70. labels=labels,
  71. title="Precision-Recall Curve for Spam Detection",
  72. )
  73. run.log({"pr-curve": pr_curve})
  74. ```
  75. """
  76. np = util.get_module(
  77. "numpy",
  78. required="roc requires the numpy library, install with `pip install numpy`",
  79. )
  80. pd = util.get_module(
  81. "pandas",
  82. required="roc requires the pandas library, install with `pip install pandas`",
  83. )
  84. sklearn_metrics = util.get_module(
  85. "sklearn.metrics",
  86. "roc requires the scikit library, install with `pip install scikit-learn`",
  87. )
  88. sklearn_utils = util.get_module(
  89. "sklearn.utils",
  90. "roc requires the scikit library, install with `pip install scikit-learn`",
  91. )
  92. def _step(x):
  93. y = np.array(x)
  94. for i in range(1, len(y)):
  95. y[i] = max(y[i], y[i - 1])
  96. return y
  97. y_true = np.array(y_true)
  98. y_probas = np.array(y_probas)
  99. if not test_missing(y_true=y_true, y_probas=y_probas):
  100. return
  101. if not test_types(y_true=y_true, y_probas=y_probas):
  102. return
  103. classes = np.unique(y_true)
  104. if classes_to_plot is None:
  105. classes_to_plot = classes
  106. precision = {}
  107. interp_recall = np.linspace(0, 1, interp_size)[::-1]
  108. indices_to_plot = np.where(np.isin(classes, classes_to_plot))[0]
  109. for i in indices_to_plot:
  110. if labels is not None and (
  111. isinstance(classes[i], int) or isinstance(classes[0], np.integer)
  112. ):
  113. class_label = labels[classes[i]]
  114. else:
  115. class_label = classes[i]
  116. cur_precision, cur_recall, _ = sklearn_metrics.precision_recall_curve(
  117. y_true, y_probas[:, i], pos_label=classes[i]
  118. )
  119. # smooth the precision (monotonically increasing)
  120. cur_precision = _step(cur_precision)
  121. # reverse order so that recall in ascending
  122. cur_precision = cur_precision[::-1]
  123. cur_recall = cur_recall[::-1]
  124. indices = np.searchsorted(cur_recall, interp_recall, side="left")
  125. precision[class_label] = cur_precision[indices]
  126. df = pd.DataFrame(
  127. {
  128. "class": np.hstack([[k] * len(v) for k, v in precision.items()]),
  129. "precision": np.hstack(list(precision.values())),
  130. "recall": np.tile(interp_recall, len(precision)),
  131. }
  132. ).round(3)
  133. if len(df) > wandb.Table.MAX_ROWS:
  134. wandb.termwarn(
  135. f"Table has a limit of {wandb.Table.MAX_ROWS} rows. Resampling to fit."
  136. )
  137. # different sampling could be applied, possibly to ensure endpoints are kept
  138. df = sklearn_utils.resample(
  139. df,
  140. replace=False,
  141. n_samples=wandb.Table.MAX_ROWS,
  142. random_state=42,
  143. stratify=df["class"],
  144. ).sort_values(["precision", "recall", "class"])
  145. return plot_table(
  146. data_table=wandb.Table(dataframe=df),
  147. vega_spec_name="wandb/area-under-curve/v0",
  148. fields={
  149. "x": "recall",
  150. "y": "precision",
  151. "class": "class",
  152. },
  153. string_fields={
  154. "title": title,
  155. "x-axis-title": "Recall",
  156. "y-axis-title": "Precision",
  157. },
  158. split_table=split_table,
  159. )