Skip to content
BIASED
Back to topic

Optional

Precision, recall and F1 from a confusion matrix

Compute TP/FP/FN → P/R/F1; match expected numbers. Self-check in the notebook.

Version
v1
Minutes
~15
Evidence
Self-check in the notebook

Until platform auto-check exists, compare cell output with the expected numbers in the notebook. This is not a debt and does not affect mastery.

Download .ipynb

Download the notebook and run it locally. Its environment requirements are listed inside.

Notebook contents

Readable on your phone. The code below has not been executed in the browser; download the notebook to run it.

ML · Precision, recall и F1 / Precision, recall, F1

Activity version: 1 · Seed: n/a · Данные: 15 меток, TP=7, FP=2, FN=1.

Ожидаемые числа
Quantity Value Tolerance
TP, FP, FN 7, 2, 1 exact
precision 7/9 ≈ 0.777… exact fraction
recall 7/8 = 0.875 exact
F1 2PR/(P+R) exact
Самопроверка в ноутбуке

Не влияет на mastery.

import numpy as np
 
y_true = np.array([0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1])
y_pred = np.array([0,0,0,0,0,1,1, 0,1,1,1,1,1,1,1])
tp = int(((y_true == 1) & (y_pred == 1)).sum())
fp = int(((y_true == 0) & (y_pred == 1)).sum())
fn = int(((y_true == 1) & (y_pred == 0)).sum())
precision = tp / (tp + fp)
recall = tp / (tp + fn)
f1 = 2 * precision * recall / (precision + recall)
print(tp, fp, fn, precision, recall, f1)
assert (tp, fp, fn) == (7, 2, 1)
assert abs(precision - 7/9) < 1e-12
assert abs(recall - 7/8) < 1e-12
assert abs(f1 - 2*(7/9)*(7/8)/((7/9)+(7/8))) < 1e-12
print("OK: precision recall F1")
 
Самопроверка в ноутбуке
  • TP/FP/FN верны
  • P, R, F1 совпали с формулами