Download src/kernel_transfer/metrics.py from Diveshj/sorghum-kernel-transfer: direct link, hf CLI and curl.
- Browser
- Download file 2.06 kB
-
https://huggingface.co/Diveshj/sorghum-kernel-transfer/resolve/main/src/kernel_transfer/metrics.py
- Command line
-
hf download hf://Diveshj/sorghum-kernel-transfer/src/kernel_transfer/metrics.py
-
curl -L -o metrics.py https://huggingface.co/Diveshj/sorghum-kernel-transfer/resolve/main/src/kernel_transfer/metrics.py
2.06 kB
| """The scores we report, written so each one can be read in a few lines. | |
| Macro-F1 is the main score. For every class we compute its F1 (a mix of precision and recall) | |
| and then take the plain average over the eight classes, so the rare Heat-Damaged class counts | |
| as much as the huge Normal class. | |
| """ | |
| import numpy as np | |
| from .data import CLASS_ORDER | |
| HD = CLASS_ORDER.index("HD") # Heat-Damaged, the rare class we always report separately | |
| def confusion_counts(y_true, y_pred, n_classes=8): | |
| """For each class: true positives, false positives, false negatives (three arrays of length n_classes).""" | |
| y_true, y_pred = np.asarray(y_true), np.asarray(y_pred) | |
| tp = np.array([np.sum((y_pred == c) & (y_true == c)) for c in range(n_classes)], dtype=float) | |
| fp = np.array([np.sum((y_pred == c) & (y_true != c)) for c in range(n_classes)], dtype=float) | |
| fn = np.array([np.sum((y_pred != c) & (y_true == c)) for c in range(n_classes)], dtype=float) | |
| return tp, fp, fn | |
| def f1_from_counts(tp, fp, fn): | |
| """F1 per class from the three count arrays (0 if a class never occurs and is never predicted).""" | |
| return 2 * tp / np.maximum(2 * tp + fp + fn, 1e-9) | |
| def macro_f1(y_true, y_pred, labels=None): | |
| """Average F1 over the classes. `labels` limits the average to some classes (default: all eight).""" | |
| tp, fp, fn = confusion_counts(y_true, y_pred) | |
| f1 = f1_from_counts(tp, fp, fn) | |
| return float(f1.mean() if labels is None else f1[list(labels)].mean()) | |
| def hd_f1(y_true, y_pred): | |
| """F1 of the Heat-Damaged class alone.""" | |
| tp, fp, fn = confusion_counts(y_true, y_pred) | |
| return float(f1_from_counts(tp, fp, fn)[HD]) | |
| def per_class_recall(y_true, y_pred): | |
| """Share of each class's crops that were found, as a list in CLASS_ORDER.""" | |
| tp, _, fn = confusion_counts(y_true, y_pred) | |
| return (tp / np.maximum(tp + fn, 1e-9)).tolist() | |
| def worst_class_recall(y_true, y_pred): | |
| """Recall of the weakest class (the number experiment C tries to raise).""" | |
| return float(min(per_class_recall(y_true, y_pred))) | |