Home Topics Model Evaluation

Model Evaluation

Measure your model's true performance

4 hours 15 examples Intermediate
Basics

Why Evaluate Models?

Accuracy isn't everything! A model that correctly predicts 99% of cases might still be terrible. Understanding when your model fails is crucial.

The Accuracy Paradox

Imagine detecting a rare disease that affects 1% of people. A model that always predicts "healthy" has 99% accuracy but is completely useless! This is why we need multiple metrics.

Basics

The Confusion Matrix

A confusion matrix shows exactly where your model is right and wrong. It's the foundation of all classification metrics.

Predicted
Positive Negative
Actual Positive TP (True Positive) FN (False Negative)
Negative FP (False Positive) TN (True Negative)

TP - True Positive ✓

Predicted positive, was positive (Correct!)

TN - True Negative ✓

Predicted negative, was negative (Correct!)

FP - False Positive ✗

Predicted positive, was negative (Type I Error)

FN - False Negative ✗

Predicted negative, was positive (Type II Error)

confusion_matrix.py
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
import matplotlib.pyplot as plt

# True labels and predictions
y_true = [1, 0, 1, 1, 0, 1, 0, 0]
y_pred = [1, 0, 0, 1, 0, 1, 1, 0]

# Generate confusion matrix
cm = confusion_matrix(y_true, y_pred)
print("Confusion Matrix:")
print(cm)
print(f"\nTN={cm[0,0]}, FP={cm[0,1]}, FN={cm[1,0]}, TP={cm[1,1]}")
Output
Confusion Matrix:
[[3 1]
 [1 3]]

TN=3, FP=1, FN=1, TP=3
Metrics

Classification Metrics

Accuracy

(TP + TN) / Total

Overall correct predictions. Good for balanced datasets.

Precision

TP / (TP + FP)

"Of all positive predictions, how many were correct?" Use when FP is costly (spam detection).

Recall (Sensitivity)

TP / (TP + FN)

"Of all actual positives, how many did we find?" Use when FN is costly (disease detection).

F1 Score

2 × (Precision × Recall) / (Precision + Recall)

Harmonic mean of Precision and Recall. Best single metric for imbalanced data.

classification_metrics.py
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.metrics import classification_report

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

print("Individual Metrics:")
print(f"  Accuracy:  {accuracy_score(y_true, y_pred):.2f}")
print(f"  Precision: {precision_score(y_true, y_pred):.2f}")
print(f"  Recall:    {recall_score(y_true, y_pred):.2f}")
print(f"  F1 Score:  {f1_score(y_true, y_pred):.2f}")

print("\n📊 Full Classification Report:")
print(classification_report(y_true, y_pred, target_names=['Negative', 'Positive']))
Output
Individual Metrics:
  Accuracy:  0.75
  Precision: 0.75
  Recall:    0.75
  F1 Score:  0.75

📊 Full Classification Report:
              precision    recall  f1-score   support

    Negative       0.75      0.75      0.75         4
    Positive       0.75      0.75      0.75         4

    accuracy                           0.75         8
   macro avg       0.75      0.75      0.75         8
weighted avg       0.75      0.75      0.75         8
Metrics

Regression Metrics

For predicting continuous values (prices, temperatures), we use different metrics:

regression_metrics.py
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
import numpy as np

# Actual vs Predicted house prices (in $1000s)
y_true = [200, 250, 300, 350, 400]
y_pred = [210, 240, 320, 330, 390]

mae = mean_absolute_error(y_true, y_pred)
mse = mean_squared_error(y_true, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y_true, y_pred)

print("Regression Metrics:")
print(f"  MAE (Mean Absolute Error):  ${mae:.0f}k")
print(f"  MSE (Mean Squared Error):   {mse:.0f}")
print(f"  RMSE (Root MSE):            ${rmse:.2f}k")
print(f"  R² Score:                   {r2:.4f}")
print(f"\n💡 On average, predictions are off by ${mae:.0f}k")
Output
Regression Metrics:
  MAE (Mean Absolute Error):  $14k
  MSE (Mean Squared Error):   260
  RMSE (Root MSE):            $16.12k
  R² Score:                   0.9740

💡 On average, predictions are off by $14k

Metric Interpretation

  • • MAE: Average absolute difference. Easy to interpret.
  • • RMSE: Penalizes large errors more. Use when outliers matter.
  • • R²: 0 to 1 score. 1.0 = perfect. How well variance is explained.
Advanced

Cross-Validation

K-Fold Cross-Validation gives a more reliable estimate by training on multiple splits of the data.

cross_validation.py
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_iris

# Load data
X, y = load_iris(return_X_y=True)
model = LogisticRegression(max_iter=200)

# 5-Fold Cross Validation
scores = cross_val_score(model, X, y, cv=5, scoring='accuracy')

print("5-Fold Cross-Validation Results:")
print(f"  Fold scores: {scores}")
print(f"  Mean: {scores.mean():.4f}")
print(f"  Std:  {scores.std():.4f}")
print(f"\n🎯 Report as: {scores.mean()*100:.1f}% ± {scores.std()*100:.1f}%")
Output
5-Fold Cross-Validation Results:
  Fold scores: [0.9667 0.9667 0.9333 0.9667 1.    ]
  Mean: 0.9667
  Std:  0.0211

🎯 Report as: 96.7% ± 2.1%

🎉 You've Mastered Model Evaluation!

Now learn Natural Language Processing to work with text data.