Before you start
Accuracy hides everything that matters on an imbalanced dataset. A model that always predicts the majority class can score 99% and be useless. Precision and recall are what you actually report.
Given y_true and y_pred, both (n,) arrays of labels in {0, 1}, compute:
precision = TP / (TP + FP)
recall = TP / (TP + FN)
f1 = 2 * precision * recall / (precision + recall)
where TP counts positions predicted 1 and truly 1, FP predicted 1 but truly
0, and FN predicted 0 but truly 1.
If any denominator is zero, that metric is 0.0. Return the three values as a
tuple of floats in the order (precision, recall, f1).
def precision_recall_f1(y_true, y_pred):
Input
y_true = np.array([1, 1, 0, 0, 1])
y_pred = np.array([1, 0, 0, 1, 1])
precision_recall_f1(y_true, y_pred)
Output
(0.6666666666666666, 0.6666666666666666, 0.6666666666666666)
Reasoning
TP = 2 (positions 0 and 4), FP = 1 (position 3) and FN = 1 (position 1). Precision and recall are both 2/3, so F1 is 2/3 too.
0.0.(precision, recall, f1).Check runs the visible cases against a fresh kernel. Submit runs the hidden ones too.
⇧↵run cell