F1 Score
F1 Score
The perfect balance between Precision and Recall — one metric to rule them both.
What is the F1 Score?
The F1 Score is a Machine Learning evaluation metric that combines Precision and Recall into a single value using their harmonic mean.
Why is the F1 Score Important?
- Balances Precision and Recall.
- Especially useful for imbalanced datasets.
- Helps when both False Positives and False Negatives matter.
- Provides a single, easy-to-compare number.
- Used in NLP, healthcare, fraud detection, and more.
Mathematical Formula
Range:
- 0 = Worst possible score
- 1 = Perfect Precision and Recall
Why Harmonic Mean Instead of Average?
If we used a simple average, a model with very high Precision and low Recall could still appear "good". But the harmonic mean ensures that:
- Both Precision and Recall must be high to get a high F1 score.
- A weak metric pulls the overall score down.
Visual Intuition Using Confusion Matrix
| Predicted Positive | Predicted Negative | |
|---|---|---|
| Actual Positive | TP | FN |
| Actual Negative | FP | TN |
F1 Score uses both Precision (TP / (TP + FP)) and Recall (TP / (TP + FN)) to balance them.
Simple Example
Suppose a model has:
- Precision = 80%
- Recall = 60%
When Should You Use F1 Score?
Use F1 Score when:
- You have an imbalanced dataset.
- Both False Positives and False Negatives are important.
- You need a single score combining Precision and Recall.
- You're comparing multiple models.
Where is F1 Score Used?
Medical Diagnosis
- Balance false alarms & missed cases
- Improve diagnostic accuracy
Fraud Detection
- Detect real fraud cases
- Avoid blocking valid users
Spam Detection
- Filter spam efficiently
- Don't block valid emails
NLP / Search Engines
- Improve precision-recall balance
- Show relevant results
Anomaly Detection
- Catch real anomalies
- Limit false alerts
Cybersecurity
- Detect attacks accurately
- Maintain user trust
High vs Low F1 Score
High F1 Score
- Balanced Precision & Recall
- Strong model performance
- Reliable predictions
Low F1 Score
- Imbalanced Precision & Recall
- Weak performance
- Many wrong predictions
Real-Life Analogy
F1 Score = Teamwork
If one player on a team is excellent but the other is weak, the team performs poorly. F1 Score works the same way — it ensures Precision and Recall work together, not separately.
Python Example — Calculating F1 Score
pip install scikit-learn
from sklearn.metrics import f1_score
y_true = [1, 0, 1, 1, 0, 1, 0, 0, 1, 1]
y_pred = [1, 0, 1, 0, 0, 1, 1, 1, 1, 1]
f1 = f1_score(y_true, y_pred)
print(f"F1 Score: {f1 * 100:.2f}%")
Full Example — Using ML Model
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import f1_score, classification_report
# Load dataset
data = load_breast_cancer()
X, y = data.data, data.target
# Split data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Train model
model = RandomForestClassifier()
model.fit(X_train, y_train)
# Predict
y_pred = model.predict(X_test)
# Evaluate
print("F1 Score:", f1_score(y_test, y_pred))
print("\nClassification Report:\n", classification_report(y_test, y_pred))
F1 Score in Multi-Class Classification
- Macro F1 — average of all class F1 scores (equal weight).
- Weighted F1 — average weighted by class frequency.
- Micro F1 — calculates F1 globally.
f1_score(y_test, y_pred, average="macro")
f1_score(y_test, y_pred, average="weighted")
f1_score(y_test, y_pred, average="micro")
F1 Score vs Accuracy
| Aspect | F1 Score | Accuracy |
|---|---|---|
| Focus | Balance of Precision & Recall | All predictions |
| Best For | Imbalanced data | Balanced data |
| Reduces | FP + FN trade-offs | Total errors |
| Use Case | Fraud, healthcare | General classification |
F1 Score vs Precision vs Recall
| Metric | Focus | Best Use |
|---|---|---|
| Precision | Correctness of positive predictions | Avoid False Positives |
| Recall | Capture of actual positives | Avoid False Negatives |
| F1 Score | Balance of both | Both errors matter |
Advantages of F1 Score
- Provides a balanced view of performance.
- Works well for imbalanced data.
- Easy to interpret.
- Helps compare different models fairly.
- Single metric to optimize.
Disadvantages
F-Beta Score (Generalized F1)
The F-Beta Score allows weighting Recall more or less than Precision.
- β = 1 → F1 Score (equal weight)
- β > 1 → Recall more important
- β < 1 → Precision more important
from sklearn.metrics import fbeta_score
fbeta_score(y_true, y_pred, beta=2)
Common Mistakes to Avoid
Best Practices
Quick Tips
- Use F1 when both errors matter.
- Combine with Precision, Recall, ROC-AUC.
- Use Macro/Micro/Weighted F1 for multi-class.
- Use F-Beta for custom trade-offs.
- Always check confusion matrix.
- Validate using cross-validation.
Importance of F1 Score
Balanced View
- Combines Precision & Recall
- Single performance number
Critical for Imbalanced Data
- Reveals real performance
- Better than Accuracy
Foundation Metric
- Used in many ML competitions
- Industry-standard metric
Business Decisions
- Improves trust in predictions
- Supports critical operations
Golden Rule
Key Takeaway
The F1 Score is the perfect balance between Precision and Recall. When your dataset is imbalanced or when both False Positives and False Negatives matter, F1 Score becomes one of the most important metrics. It provides a single, balanced number to evaluate and compare Machine Learning models effectively.