Concepts 🚀 Project 🧮 Labs
🧮 Labs / ML Advanced / Overfitting — the #1 reason ML models fail in production

Overfitting — the #1 reason ML models fail in production

Understand the bias-variance tradeoff, why train > test means overfitting, and 5 techniques to fix it. This is what separates seniors from freshers.

script.py v3.1
Python output click Run to execute
Click "Run" to execute the code on the left.
The output will appear here.
🧠 How it works

Overfitting = model memorizes training data instead of learning patterns. Symptom: train R² = 0.99, test R² = 0.50. The gap = overfitting. BIAS-VARIANCE TRADEOFF: High bias (underfitting): model too simple. train + test both low. High variance (overfitting): model too complex. train high, test low. Sweet spot: train ≈ test, both high. WHY IT MATTERS: production = new data = the test set scenario. A model that's 99% on train but 50% on test is WORTHLESS in production. 5 FIXES: (1) More data — best fix. Can't memorize 1M rows. (2) Simpler model — reduce degree/depth/layers. (3) Regularization — L1 (Lasso) zeros out useless features. L2 (Ridge) shrinks coefficients. (4) Cross-validation — 5-fold CV shows if the model generalizes. (5) Early stopping — stop when validation score drops. ALWAYS report train + test scores. If someone only shows train, assume they're hiding overfitting.

✏️ Try these changes
  • Change degree 15 to 25
    → even more extreme overfitting — test R² very negative
  • Increase n from 30 to 300
    → more data → less overfitting, even at degree 15
  • Change noise from 0.2 to 1.0
    → harder problem — all models do worse
  • Add Ridge regression to the pipeline: from sklearn.linear_model import Ridge
    → regularization reduces overfitting