Python ML Precision, Recall, F1 and ROC-AUC
Precision, recall, F1 and ROC-AUC are four scores that look past accuracy. Each one answers a different question about the mistakes.
Precision and recall by hand
Four true positives, one false positive, and one false negative give precision 0.8 and recall 0.8.
tp = 4
fp = 1
fn = 1
print(round(tp / (tp + fp), 2))
print(round(tp / (tp + fn), 2))The same scores from sklearn
precision_score() and recall_score() agree with the hand counts. f1_score() balances the two at 0.8.
from sklearn.metrics import precision_score, recall_score, f1_score
y_true = [1, 1, 0, 1, 0, 0, 1, 0, 0, 1]
y_pred = [1, 0, 0, 1, 0, 1, 1, 0, 0, 1]
print(round(precision_score(y_true, y_pred), 2))
print(round(recall_score(y_true, y_pred), 2))
print(round(f1_score(y_true, y_pred), 2))ROC-AUC from scores
roc_auc_score() takes the true labels and the model scores. A score of 0.92 means the ranking is strong.
from sklearn.metrics import roc_auc_score
y_true = [1, 1, 0, 1, 0, 0, 1, 0, 0, 1]
y_scores = [0.9, 0.4, 0.2, 0.8, 0.3, 0.7, 0.6, 0.1, 0.2, 0.85]
print(round(roc_auc_score(y_true, y_scores), 2))Example
from sklearn.metrics import precision_score, recall_score, f1_score, roc_auc_score
y_true = [1, 1, 0, 1, 0, 0, 1, 0, 0, 1]
y_pred = [1, 0, 0, 1, 0, 1, 1, 0, 0, 1]
y_scores = [0.9, 0.4, 0.2, 0.8, 0.3, 0.7, 0.6, 0.1, 0.2, 0.85]
tp = 4
fp = 1
fn = 1
print("Hand precision:", round(tp / (tp + fp), 2))
print("Hand recall:", round(tp / (tp + fn), 2))
print("sklearn precision:", round(precision_score(y_true, y_pred), 2))
print("sklearn recall:", round(recall_score(y_true, y_pred), 2))
print("sklearn F1:", round(f1_score(y_true, y_pred), 2))
print("sklearn ROC-AUC:", round(roc_auc_score(y_true, y_scores), 2))Key points
- Precision: of the cases the model calls positive, how many are truly positive
- Recall: of the truly positive cases, how many the model finds
- F1: one score that balances precision and recall
- ROC-AUC: how well the model ranks positives above negatives, from 0.5 to 1
- Use precision_score(), recall_score() and f1_score() from sklearn.metrics
- Use roc_auc_score() with true labels and model scores, not hard predictions
- Pick precision when a false alarm is costly. Pick recall when a miss is costly.
In this example, ten items carry true labels, predicted labels, and model scores. Counting by hand gives 4 true positives, 1 false positive, and 1 false negative. Hand precision is 0.8, and hand recall is 0.8. sklearn gives the same precision and recall, an F1 of 0.8, and a ROC-AUC of 0.92. The hand counts and the library agree, so the scores are checked, not just trusted.
Note
A model can have high precision and low recall at the same time.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
A missed cancer case is far worse than a false alarm. Which score matters most?