File size: 2,058 Bytes
02a1d81 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | """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)))
|