CodeBlanks Logo Icon CodeBlanks

F1 score

F1 score is the harmonic mean of precision and recall.

The F1 score

F1 is the harmonic mean of precision and recall: 2·P·R / (P + R). If either is low, F1 is low too; an arithmetic mean would hide this.

P, R = 1.0, 0.1
print((P + R) / 2)           # 0.55  misleading
print(2 * P * R / (P + R))   # 0.18  realistic

It is often used as a single summary metric in imbalanced problems where both false alarms and misses matter.

classification_report

classification_report gives the precision, recall, F1 and support (example count) for each class in a single table:

from sklearn.metrics import classification_report
print(classification_report(y_test, y_pred, digits=3))

In the bottom rows, macro avg weights classes equally and weighted avg by class size.

Practice Four metrics

For the given labels, print accuracy, precision, recall and F1 with round(..., 3) in a single print, separated by spaces.

Starter code

model.py
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score

y_true = [1, 1, 1, 1, 0, 0, 0, 0, 0, 0]
y_pred = [1, 1, 1, 0, 1, 0, 0, 0, 0, 0]

# buraya yaz

Sample solution

model.py
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score

y_true = [1, 1, 1, 1, 0, 0, 0, 0, 0, 0]
y_pred = [1, 1, 1, 0, 1, 0, 0, 0, 0, 0]

print(round(accuracy_score(y_true, y_pred), 3), round(precision_score(y_true, y_pred), 3), round(recall_score(y_true, y_pred), 3), round(f1_score(y_true, y_pred), 3))

Expected output

0.8 0.75 0.75 0.75

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 If precision is 0.5 and recall is 0.5, what is F1?

  • 1.0
  • 0.75
  • 0.5 Correct answer
  • 0.25

Explanation: 2 · 0.5 · 0.5 / (0.5 + 0.5) = 0.5; if both are equal, F1 is the same.

2 Compute the F1 score.

Question
f = ____(y_true, y_pred)
Answer
f = f1_score(y_true, y_pred)

Explanation: f1_score gives the harmonic mean of precision and recall.

3 Match the report rows.

Term Meaning
precision Hit rate when saying positive
recall Share of positives caught
f1-score Harmonic mean
support Examples in the class

All lessons in Beginner

13 Project: Classification

  1. Preparing data
  2. Training model
  3. Prediction
  4. Evaluation