🤖 AI/ML

F1 Score

F1 Score

The harmonic mean of precision and recall. Used to evaluate classification models.

📖 Detailed Explanation

The F1 Score is the harmonic mean of precision and recall, an evaluation metric that expresses a classification model's performance as a single number. It is calculated by the formula F1 = 2 * (Precision * Recall) / (Precision + Recall) and takes a value between 0 and 1. The closer it is to 1, the better the model's performance.

The F1 Score was first proposed in 2003 in the field of information retrieval and has since become established as a standard evaluation metric in machine learning. The harmonic mean is used because the F1 Score drops sharply if either precision or recall is low. This is particularly useful in situations where balance between the two metrics is important.

The core principle is based on True Positive (TP), False Positive (FP), and False Negative (FN). Precision is TP/(TP+FP), the proportion of actual positives among those the model predicted as positive, and recall is TP/(TP+FN), the proportion of actual positives that the model found. The F1 Score presents the balance point between the two.

In practice, the F1 Score is especially important for datasets with severe class imbalance. For example, in fraud detection, if fraud cases account for 1% of the total, simple accuracy can reach 99%, but the F1 Score reflects actual detection capability more accurately. It is used as a key metric in spam filters, medical diagnosis, anomaly detection, and more.

💻 Code Example

from sklearn.metrics import f1_score, precision_score, recall_score, classification_report
import numpy as np

# 실제 레이블과 예측 레이블
y_true = [1, 0, 1, 1, 0, 1, 0, 0, 1, 1]
y_pred = [1, 0, 1, 0, 0, 1, 1, 0, 0, 1]

# F1 Score 계산 (binary classification)
f1 = f1_score(y_true, y_pred)
precision = precision_score(y_true, y_pred)
recall = recall_score(y_true, y_pred)

print(f"Precision: {precision:.4f}")  # 0.8000
print(f"Recall: {recall:.4f}")        # 0.6667
print(f"F1 Score: {f1:.4f}")          # 0.7273

# 수동 계산 검증
f1_manual = 2 * (precision * recall) / (precision + recall)
print(f"수동 계산 F1: {f1_manual:.4f}")

# 멀티클래스 F1 Score
y_true_multi = [0, 1, 2, 0, 1, 2, 0, 1, 2]
y_pred_multi = [0, 2, 1, 0, 0, 2, 0, 1, 2]

# 다양한 averaging 방식
print("\n멀티클래스 F1 Score:")
print(f"Macro F1: {f1_score(y_true_multi, y_pred_multi, average='macro'):.4f}")
print(f"Micro F1: {f1_score(y_true_multi, y_pred_multi, average='micro'):.4f}")
print(f"Weighted F1: {f1_score(y_true_multi, y_pred_multi, average='weighted'):.4f}")

# 상세 리포트
print("\n분류 리포트:")
print(classification_report(y_true_multi, y_pred_multi,
                          target_names=['Class 0', 'Class 1', 'Class 2']))

🗣️ Say It Like This in Practice

In the ML team weekly meeting

"The fraud detection model's accuracy is 99%, but it is catching only 30% of actual fraud cases. By F1 Score it is only 0.45, so we need to adjust the threshold in the direction of raising Recall. Even if Precision drops a little, we will tune toward an F1 Score of 0.6 or higher."

In an ML engineer interview

"The reason for using the F1 Score is that model performance cannot be properly evaluated by accuracy alone on imbalanced data. Because it uses the harmonic mean, the score drops sharply if either precision or recall is low, so both metrics must be kept above a certain level."

In a model review meeting

"For a medical diagnosis model, I think it would be better to use Weighted F1 rather than Macro F1. Since the frequency of occurrence differs by disease, we need to calculate with weights to better reflect actual performance. The current Weighted F1 is 0.82, but the Recall for rare disease classes is low, so we are considering data augmentation."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

1
Choosing an averaging method when class imbalance is severe

Macro F1 treats all classes equally, and Weighted F1 applies weights proportional to the number of samples. Use Macro F1 when minority classes are important (such as cancer diagnosis), and Weighted F1 when overall performance is important.

2
Understanding the trade-off between Precision and Recall

Even if the F1 Score is high, depending on the business objective either Precision or Recall may be more important. For spam filters, Precision is more important, and for cancer diagnosis, Recall is more important. Do not look only at the F1 Score; check the individual metrics as well.

3
Caution when tuning the probability threshold

The F1 Score at the default threshold of 0.5 may not be optimal. Plot the Precision-Recall curve to find the optimal threshold for your objective. Lowering the threshold raises Recall and lowers Precision.

🔗 Related Terms

📚 Learn More