confusion_matrix.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. from __future__ import annotations
  2. from typing import TYPE_CHECKING, Sequence, TypeVar
  3. import wandb
  4. from wandb import util
  5. from wandb.plot.custom_chart import plot_table
  6. if TYPE_CHECKING:
  7. from wandb.plot.custom_chart import CustomChart
  8. T = TypeVar("T")
  9. def confusion_matrix(
  10. probs: Sequence[Sequence[float]] | None = None,
  11. y_true: Sequence[T] | None = None,
  12. preds: Sequence[T] | None = None,
  13. class_names: Sequence[str] | None = None,
  14. title: str = "Confusion Matrix Curve",
  15. split_table: bool = False,
  16. ) -> CustomChart:
  17. """Constructs a confusion matrix from a sequence of probabilities or predictions.
  18. Args:
  19. probs: A sequence of predicted probabilities for each
  20. class. The sequence shape should be (N, K) where N is the number of samples
  21. and K is the number of classes. If provided, `preds` should not be provided.
  22. y_true: A sequence of true labels.
  23. preds: A sequence of predicted class labels. If provided,
  24. `probs` should not be provided.
  25. class_names: Sequence of class names. If not
  26. provided, class names will be defined as "Class_1", "Class_2", etc.
  27. title: Title of the confusion matrix chart.
  28. split_table: Whether the table should be split into a separate section
  29. in the W&B UI. If `True`, the table will be displayed in a section named
  30. "Custom Chart Tables". Default is `False`.
  31. Returns:
  32. CustomChart: A custom chart object that can be logged to W&B. To log the
  33. chart, pass it to `wandb.log()`.
  34. Raises:
  35. ValueError: If both `probs` and `preds` are provided or if the number of
  36. predictions and true labels are not equal. If the number of unique
  37. predicted classes exceeds the number of class names or if the number of
  38. unique true labels exceeds the number of class names.
  39. wandb.Error: If numpy is not installed.
  40. Examples:
  41. Logging a confusion matrix with random probabilities for wildlife
  42. classification:
  43. ```python
  44. import numpy as np
  45. import wandb
  46. # Define class names for wildlife
  47. wildlife_class_names = ["Lion", "Tiger", "Elephant", "Zebra"]
  48. # Generate random true labels (0 to 3 for 10 samples)
  49. wildlife_y_true = np.random.randint(0, 4, size=10)
  50. # Generate random probabilities for each class (10 samples x 4 classes)
  51. wildlife_probs = np.random.rand(10, 4)
  52. wildlife_probs = np.exp(wildlife_probs) / np.sum(
  53. np.exp(wildlife_probs),
  54. axis=1,
  55. keepdims=True,
  56. )
  57. # Initialize W&B run and log confusion matrix
  58. with wandb.init(project="wildlife_classification") as run:
  59. confusion_matrix = wandb.plot.confusion_matrix(
  60. probs=wildlife_probs,
  61. y_true=wildlife_y_true,
  62. class_names=wildlife_class_names,
  63. title="Wildlife Classification Confusion Matrix",
  64. )
  65. run.log({"wildlife_confusion_matrix": confusion_matrix})
  66. ```
  67. In this example, random probabilities are used to generate a confusion
  68. matrix.
  69. Logging a confusion matrix with simulated model predictions and 85%
  70. accuracy:
  71. ```python
  72. import numpy as np
  73. import wandb
  74. # Define class names for wildlife
  75. wildlife_class_names = ["Lion", "Tiger", "Elephant", "Zebra"]
  76. # Simulate true labels for 200 animal images (imbalanced distribution)
  77. wildlife_y_true = np.random.choice(
  78. [0, 1, 2, 3],
  79. size=200,
  80. p=[0.2, 0.3, 0.25, 0.25],
  81. )
  82. # Simulate model predictions with 85% accuracy
  83. wildlife_preds = [
  84. y_t
  85. if np.random.rand() < 0.85
  86. else np.random.choice([x for x in range(4) if x != y_t])
  87. for y_t in wildlife_y_true
  88. ]
  89. # Initialize W&B run and log confusion matrix
  90. with wandb.init(project="wildlife_classification") as run:
  91. confusion_matrix = wandb.plot.confusion_matrix(
  92. preds=wildlife_preds,
  93. y_true=wildlife_y_true,
  94. class_names=wildlife_class_names,
  95. title="Simulated Wildlife Classification Confusion Matrix",
  96. )
  97. run.log({"wildlife_confusion_matrix": confusion_matrix})
  98. ```
  99. In this example, predictions are simulated with 85% accuracy to generate a
  100. confusion matrix.
  101. """
  102. np = util.get_module(
  103. "numpy",
  104. required=(
  105. "numpy is required to use wandb.plot.confusion_matrix, "
  106. "install with `pip install numpy`",
  107. ),
  108. )
  109. if probs is not None and preds is not None:
  110. raise ValueError("Only one of `probs` or `preds` should be provided, not both.")
  111. if probs is not None:
  112. preds = np.argmax(probs, axis=1).tolist()
  113. if len(preds) != len(y_true):
  114. raise ValueError("The number of predictions and true labels must be equal.")
  115. if class_names is not None:
  116. n_classes = len(class_names)
  117. class_idx = list(range(n_classes))
  118. if len(set(preds)) > len(class_names):
  119. raise ValueError(
  120. "The number of unique predicted classes exceeds the number of class names."
  121. )
  122. if len(set(y_true)) > len(class_names):
  123. raise ValueError(
  124. "The number of unique true labels exceeds the number of class names."
  125. )
  126. else:
  127. class_idx = set(preds).union(set(y_true))
  128. n_classes = len(class_idx)
  129. class_names = [f"Class_{i + 1}" for i in range(n_classes)]
  130. # Create a mapping from class name to index
  131. class_mapping = {val: i for i, val in enumerate(sorted(list(class_idx)))}
  132. counts = np.zeros((n_classes, n_classes))
  133. for i in range(len(preds)):
  134. counts[class_mapping[y_true[i]], class_mapping[preds[i]]] += 1
  135. data = [
  136. [class_names[i], class_names[j], counts[i, j]]
  137. for i in range(n_classes)
  138. for j in range(n_classes)
  139. ]
  140. return plot_table(
  141. data_table=wandb.Table(
  142. columns=["Actual", "Predicted", "nPredictions"],
  143. data=data,
  144. ),
  145. vega_spec_name="wandb/confusion_matrix/v1",
  146. fields={
  147. "Actual": "Actual",
  148. "Predicted": "Predicted",
  149. "nPredictions": "nPredictions",
  150. },
  151. string_fields={"title": title},
  152. split_table=split_table,
  153. )