|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from collections.abc import Iterable, Sequence |
| 4 | +from typing import Any, cast |
| 5 | + |
| 6 | +import numpy as np |
| 7 | + |
| 8 | + |
| 9 | +def _is_multi_label_shaped(y: list[int] | list[str] | list[list[int]] | list[list[str]]) -> bool: |
| 10 | + """Check if the labels are in a multi-label shape.""" |
| 11 | + return isinstance(y, (list, tuple)) and len(y) > 0 and isinstance(y[0], (list, tuple, set)) |
| 12 | + |
| 13 | + |
| 14 | +def _one_hot(labels: Sequence[Any], classes: Sequence[Any]) -> np.ndarray: |
| 15 | + """One-hot encode a flat sequence of labels against a fixed set of classes.""" |
| 16 | + index = {label: position for position, label in enumerate(classes)} |
| 17 | + encoded = np.zeros((len(labels), len(classes)), dtype=int) |
| 18 | + for row, label in enumerate(labels): |
| 19 | + encoded[row, index[label]] = 1 |
| 20 | + return encoded |
| 21 | + |
| 22 | + |
| 23 | +def _multi_hot(label_lists: Iterable[Iterable[Any]], classes: Sequence[Any]) -> np.ndarray: |
| 24 | + """Multi-hot encode a sequence of label lists against a fixed set of classes.""" |
| 25 | + index = {label: position for position, label in enumerate(classes)} |
| 26 | + label_lists = list(label_lists) |
| 27 | + encoded = np.zeros((len(label_lists), len(classes)), dtype=int) |
| 28 | + for row, labels in enumerate(label_lists): |
| 29 | + for label in labels: |
| 30 | + encoded[row, index[label]] = 1 |
| 31 | + return encoded |
| 32 | + |
| 33 | + |
| 34 | +def _precision_recall_f1_support( |
| 35 | + y_true: np.ndarray, y_pred: np.ndarray |
| 36 | +) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: |
| 37 | + """Compute per-class precision, recall, f1, and support from one-hot / multi-hot encoded labels.""" |
| 38 | + true_positive = ((y_true == 1) & (y_pred == 1)).sum(axis=0).astype(float) |
| 39 | + false_positive = ((y_true == 0) & (y_pred == 1)).sum(axis=0).astype(float) |
| 40 | + false_negative = ((y_true == 1) & (y_pred == 0)).sum(axis=0).astype(float) |
| 41 | + support = y_true.sum(axis=0) |
| 42 | + |
| 43 | + predicted_positive = true_positive + false_positive |
| 44 | + actual_positive = true_positive + false_negative |
| 45 | + precision = np.divide( |
| 46 | + true_positive, predicted_positive, out=np.zeros_like(true_positive), where=predicted_positive > 0 |
| 47 | + ) |
| 48 | + recall = np.divide(true_positive, actual_positive, out=np.zeros_like(true_positive), where=actual_positive > 0) |
| 49 | + precision_plus_recall = precision + recall |
| 50 | + f1 = np.divide( |
| 51 | + 2 * precision * recall, precision_plus_recall, out=np.zeros_like(precision), where=precision_plus_recall > 0 |
| 52 | + ) |
| 53 | + |
| 54 | + return precision, recall, f1, support |
| 55 | + |
| 56 | + |
| 57 | +def evaluate_single_or_multi_label( |
| 58 | + predictions: np.ndarray, |
| 59 | + y: list[int] | list[str] | list[list[int]] | list[list[str]], |
| 60 | +) -> dict[str, dict[str, float]]: |
| 61 | + """Evaluate the classifier on a given dataset using a classification report. |
| 62 | +
|
| 63 | + This function computes per-class precision, recall and f1-score (via one-vs-rest / multi-hot encoding), plus |
| 64 | + overall accuracy, macro average, and weighted average. |
| 65 | +
|
| 66 | + :param predictions: The predictions. |
| 67 | + :param y: The ground truth labels. |
| 68 | + :return: A classification report, as a dictionary. |
| 69 | + """ |
| 70 | + if _is_multi_label_shaped(y): |
| 71 | + y = cast(list[list[str]] | list[list[int]], y) |
| 72 | + predictions = cast(np.ndarray, predictions) |
| 73 | + y_labels = {label for labels in y for label in labels} |
| 74 | + predicted_labels = {label for labels in predictions for label in labels} |
| 75 | + classes = sorted(y_labels | predicted_labels) |
| 76 | + y_transformed = _multi_hot(y, classes) |
| 77 | + predictions_transformed = _multi_hot(predictions, classes) |
| 78 | + else: |
| 79 | + y = cast(list[str] | list[int], y) |
| 80 | + classes = sorted(set(y) | set(predictions.tolist())) |
| 81 | + y_transformed = _one_hot(y, classes) |
| 82 | + predictions_transformed = _one_hot(predictions.tolist(), classes) |
| 83 | + |
| 84 | + target_names = [str(c) for c in classes] |
| 85 | + precision, recall, f1, support = _precision_recall_f1_support(y_transformed, predictions_transformed) |
| 86 | + total_support = float(support.sum()) |
| 87 | + accuracy = float(np.all(y_transformed == predictions_transformed, axis=1).mean()) |
| 88 | + |
| 89 | + report: dict[str, Any] = { |
| 90 | + name: { |
| 91 | + "precision": float(precision[idx]), |
| 92 | + "recall": float(recall[idx]), |
| 93 | + "f1-score": float(f1[idx]), |
| 94 | + "support": float(support[idx]), |
| 95 | + } |
| 96 | + for idx, name in enumerate(target_names) |
| 97 | + } |
| 98 | + report["accuracy"] = accuracy |
| 99 | + report["macro avg"] = { |
| 100 | + "precision": float(precision.mean()), |
| 101 | + "recall": float(recall.mean()), |
| 102 | + "f1-score": float(f1.mean()), |
| 103 | + "support": total_support, |
| 104 | + } |
| 105 | + weights = support / total_support if total_support > 0 else np.zeros_like(support, dtype=float) |
| 106 | + report["weighted avg"] = { |
| 107 | + "precision": float((precision * weights).sum()), |
| 108 | + "recall": float((recall * weights).sum()), |
| 109 | + "f1-score": float((f1 * weights).sum()), |
| 110 | + "support": total_support, |
| 111 | + } |
| 112 | + |
| 113 | + return report |
0 commit comments