classifier.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. """Define plots for classification models built with scikit-learn."""
  2. from warnings import simplefilter
  3. import numpy as np
  4. from sklearn import naive_bayes
  5. import wandb
  6. import wandb.plot
  7. from wandb.integration.sklearn import calculate, utils
  8. from . import shared
  9. # ignore all future warnings
  10. simplefilter(action="ignore", category=FutureWarning)
  11. def classifier(
  12. model,
  13. X_train, # noqa: N803
  14. X_test, # noqa: N803
  15. y_train,
  16. y_test,
  17. y_pred,
  18. y_probas,
  19. labels,
  20. is_binary=False,
  21. model_name="Classifier",
  22. feature_names=None,
  23. log_learning_curve=False,
  24. ):
  25. """Generate all sklearn classifier plots supported by W&B.
  26. The following plots are generated:
  27. feature importances, confusion matrix, summary metrics,
  28. class proportions, calibration curve, roc curve, precision-recall curve.
  29. Should only be called with a fitted classifier (otherwise an error is thrown).
  30. Args:
  31. model: (classifier) Takes in a fitted classifier.
  32. X_train: (arr) Training set features.
  33. y_train: (arr) Training set labels.
  34. X_test: (arr) Test set features.
  35. y_test: (arr) Test set labels.
  36. y_pred: (arr) Test set predictions by the model passed.
  37. y_probas: (arr) Test set predicted probabilities by the model passed.
  38. labels: (list) Named labels for target variable (y). Makes plots easier to
  39. read by replacing target values with corresponding index.
  40. For example if `labels=['dog', 'cat', 'owl']` all 0s are
  41. replaced by dog, 1s by cat.
  42. is_binary: (bool) Is the model passed a binary classifier? Defaults to False
  43. model_name: (str) Model name. Defaults to 'Classifier'
  44. feature_names: (list) Names for features. Makes plots easier to read by
  45. replacing feature indexes with corresponding names.
  46. log_learning_curve: (bool) Whether or not to log the learning curve.
  47. Defaults to False.
  48. Returns:
  49. None: To see plots, go to your W&B run page then expand the 'media' tab
  50. under 'auto visualizations'.
  51. Example:
  52. ```python
  53. wandb.sklearn.plot_classifier(
  54. model,
  55. X_train,
  56. X_test,
  57. y_train,
  58. y_test,
  59. y_pred,
  60. y_probas,
  61. ["cat", "dog"],
  62. False,
  63. "RandomForest",
  64. ["barks", "drools", "plays_fetch", "breed"],
  65. )
  66. ```
  67. """
  68. wandb.termlog(f"\nPlotting {model_name}.")
  69. if not isinstance(model, naive_bayes.MultinomialNB):
  70. feature_importances(model, feature_names)
  71. wandb.termlog("Logged feature importances.")
  72. if log_learning_curve:
  73. shared.learning_curve(model, X_train, y_train)
  74. wandb.termlog("Logged learning curve.")
  75. confusion_matrix(y_test, y_pred, labels)
  76. wandb.termlog("Logged confusion matrix.")
  77. shared.summary_metrics(model, X=X_train, y=y_train, X_test=X_test, y_test=y_test)
  78. wandb.termlog("Logged summary metrics.")
  79. class_proportions(y_train, y_test, labels)
  80. wandb.termlog("Logged class proportions.")
  81. if not isinstance(model, naive_bayes.MultinomialNB):
  82. calibration_curve(model, X_train, y_train, model_name)
  83. wandb.termlog("Logged calibration curve.")
  84. roc(y_test, y_probas, labels)
  85. wandb.termlog("Logged roc curve.")
  86. precision_recall(y_test, y_probas, labels)
  87. wandb.termlog("Logged precision-recall curve.")
  88. def roc(
  89. y_true=None,
  90. y_probas=None,
  91. labels=None,
  92. plot_micro=True,
  93. plot_macro=True,
  94. classes_to_plot=None,
  95. ):
  96. """Log the receiver-operating characteristic curve.
  97. Args:
  98. y_true: (arr) Test set labels.
  99. y_probas: (arr) Test set predicted probabilities.
  100. labels: (list) Named labels for target variable (y). Makes plots easier to
  101. read by replacing target values with corresponding index.
  102. For example if `labels=['dog', 'cat', 'owl']` all 0s are
  103. replaced by dog, 1s by cat.
  104. Returns:
  105. None: To see plots, go to your W&B run page then expand the 'media' tab
  106. under 'auto visualizations'.
  107. Example:
  108. ```python
  109. wandb.sklearn.plot_roc(y_true, y_probas, labels)
  110. ```
  111. """
  112. roc_chart = wandb.plot.roc_curve(y_true, y_probas, labels, classes_to_plot)
  113. wandb.log({"roc": roc_chart})
  114. def confusion_matrix(
  115. y_true=None,
  116. y_pred=None,
  117. labels=None,
  118. true_labels=None,
  119. pred_labels=None,
  120. normalize=False,
  121. ):
  122. """Log a confusion matrix to W&B.
  123. Confusion matrices depict the pattern of misclassifications by a model.
  124. Args:
  125. y_true: (arr) Test set labels.
  126. y_probas: (arr) Test set predicted probabilities.
  127. labels: (list) Named labels for target variable (y). Makes plots easier to
  128. read by replacing target values with corresponding index.
  129. For example if `labels=['dog', 'cat', 'owl']` all 0s are
  130. replaced by dog, 1s by cat.
  131. Returns:
  132. None: To see plots, go to your W&B run page then expand the 'media' tab
  133. under 'auto visualizations'.
  134. Example:
  135. ```python
  136. wandb.sklearn.plot_confusion_matrix(y_true, y_probas, labels)
  137. ```
  138. """
  139. y_true = np.asarray(y_true)
  140. y_pred = np.asarray(y_pred)
  141. not_missing = utils.test_missing(y_true=y_true, y_pred=y_pred)
  142. correct_types = utils.test_types(y_true=y_true, y_pred=y_pred)
  143. if not_missing and correct_types:
  144. confusion_matrix_chart = calculate.confusion_matrix(
  145. y_true,
  146. y_pred,
  147. labels,
  148. true_labels,
  149. pred_labels,
  150. normalize,
  151. )
  152. wandb.log({"confusion_matrix": confusion_matrix_chart})
  153. def precision_recall(
  154. y_true=None, y_probas=None, labels=None, plot_micro=True, classes_to_plot=None
  155. ):
  156. """Log a precision-recall curve to W&B.
  157. Precision-recall curves depict the tradeoff between positive predictive value (precision)
  158. and true positive rate (recall) as the threshold of a classifier is shifted.
  159. Args:
  160. y_true: (arr) Test set labels.
  161. y_probas: (arr) Test set predicted probabilities.
  162. labels: (list) Named labels for target variable (y). Makes plots easier to
  163. read by replacing target values with corresponding index.
  164. For example if `labels=['dog', 'cat', 'owl']` all 0s are
  165. replaced by dog, 1s by cat.
  166. Returns:
  167. None: To see plots, go to your W&B run page then expand the 'media' tab
  168. under 'auto visualizations'.
  169. Example:
  170. ```python
  171. wandb.sklearn.plot_precision_recall(y_true, y_probas, labels)
  172. ```
  173. """
  174. precision_recall_chart = wandb.plot.pr_curve(
  175. y_true, y_probas, labels, classes_to_plot
  176. )
  177. wandb.log({"precision_recall": precision_recall_chart})
  178. def feature_importances(
  179. model=None, feature_names=None, title="Feature Importance", max_num_features=50
  180. ):
  181. """Log a plot depicting the relative importance of each feature for a classifier's decisions.
  182. Should only be called with a fitted classifier (otherwise an error is thrown).
  183. Only works with classifiers that have a feature_importances_ attribute, like trees.
  184. Args:
  185. model: (clf) Takes in a fitted classifier.
  186. feature_names: (list) Names for features. Makes plots easier to read by
  187. replacing feature indexes with corresponding names.
  188. Returns:
  189. None: To see plots, go to your W&B run page then expand the 'media' tab
  190. under 'auto visualizations'.
  191. Example:
  192. ```python
  193. wandb.sklearn.plot_feature_importances(model, ["width", "height", "length"])
  194. ```
  195. """
  196. not_missing = utils.test_missing(model=model)
  197. correct_types = utils.test_types(model=model)
  198. model_fitted = utils.test_fitted(model)
  199. if not_missing and correct_types and model_fitted:
  200. feature_importance_chart = calculate.feature_importances(model, feature_names)
  201. wandb.log({"feature_importances": feature_importance_chart})
  202. def class_proportions(y_train=None, y_test=None, labels=None):
  203. """Plot the distribution of target classes in training and test sets.
  204. Useful for detecting imbalanced classes.
  205. Args:
  206. y_train: (arr) Training set labels.
  207. y_test: (arr) Test set labels.
  208. labels: (list) Named labels for target variable (y). Makes plots easier to
  209. read by replacing target values with corresponding index.
  210. For example if `labels=['dog', 'cat', 'owl']` all 0s are
  211. replaced by dog, 1s by cat.
  212. Returns:
  213. None: To see plots, go to your W&B run page then expand the 'media' tab
  214. under 'auto visualizations'.
  215. Example:
  216. ```python
  217. wandb.sklearn.plot_class_proportions(y_train, y_test, ["dog", "cat", "owl"])
  218. ```
  219. """
  220. not_missing = utils.test_missing(y_train=y_train, y_test=y_test)
  221. correct_types = utils.test_types(y_train=y_train, y_test=y_test)
  222. if not_missing and correct_types:
  223. y_train, y_test = np.array(y_train), np.array(y_test)
  224. class_proportions_chart = calculate.class_proportions(y_train, y_test, labels)
  225. wandb.log({"class_proportions": class_proportions_chart})
  226. def calibration_curve(clf=None, X=None, y=None, clf_name="Classifier"): # noqa: N803
  227. """Log a plot depicting how well-calibrated the predicted probabilities of a classifier are.
  228. Also suggests how to calibrate an uncalibrated classifier. Compares estimated predicted
  229. probabilities by a baseline logistic regression model, the model passed as
  230. an argument, and by both its isotonic calibration and sigmoid calibrations.
  231. The closer the calibration curves are to a diagonal the better.
  232. A sine wave like curve represents an overfitted classifier, while a cosine
  233. wave like curve represents an underfitted classifier.
  234. By training isotonic and sigmoid calibrations of the model and comparing
  235. their curves we can figure out whether the model is over or underfitting and
  236. if so which calibration (sigmoid or isotonic) might help fix this.
  237. For more details, see https://scikit-learn.org/stable/auto_examples/calibration/plot_calibration_curve.html.
  238. Should only be called with a fitted classifier (otherwise an error is thrown).
  239. Please note this function fits variations of the model on the training set when called.
  240. Args:
  241. clf: (clf) Takes in a fitted classifier.
  242. X: (arr) Training set features.
  243. y: (arr) Training set labels.
  244. model_name: (str) Model name. Defaults to 'Classifier'
  245. Returns:
  246. None: To see plots, go to your W&B run page then expand the 'media' tab
  247. under 'auto visualizations'.
  248. Example:
  249. ```python
  250. wandb.sklearn.plot_calibration_curve(clf, X, y, "RandomForestClassifier")
  251. ```
  252. """
  253. not_missing = utils.test_missing(clf=clf, X=X, y=y)
  254. correct_types = utils.test_types(clf=clf, X=X, y=y)
  255. is_fitted = utils.test_fitted(clf)
  256. if not_missing and correct_types and is_fitted:
  257. y = np.asarray(y)
  258. if y.dtype.char == "U" or not ((y == 0) | (y == 1)).all():
  259. wandb.termwarn(
  260. "This function only supports binary classification at the moment and therefore expects labels to be binary. Skipping calibration curve."
  261. )
  262. return
  263. calibration_curve_chart = calculate.calibration_curves(clf, X, y, clf_name)
  264. wandb.log({"calibration_curve": calibration_curve_chart})