Lesson 9 of 18 · 2 min
Overfitting vs Underfitting
Underfitting: model too simple → high error on BOTH train and test Good fit: model just right → low error on train, low error on test Overfitting: model too complex → low error on train, HIGH error on test
# Detect overfitting: compare train vs test error
from sklearn.metrics import mean_squared_error
import numpy as np
train_pred = model.predict(X_train)
test_pred = model.predict(X_test)
train_rmse = np.sqrt(mean_squared_error(y_train, train_pred))
test_rmse = np.sqrt(mean_squared_error(y_test, test_pred))
print(f"Train RMSE: {train_rmse:.4f}")
print(f"Test RMSE: {test_rmse:.4f}")
# Output: Train RMSE: 0.4821 Test RMSE: 0.5103 ← small gap = good generalisation
# If test RMSE >> train RMSE → overfitting
# If both high → underfitting
# If both similar and low → good fit
