Regularization — Worked Numerical Examples
Prerequisite Knowledge
This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.
Previously Covered in This Subject
- Linear Regression — hypothesis function, cost function (MSE), gradient descent update — covered in Lecture 3 and Lecture 4
- Feature Engineering and Feature Scaling — why scaling matters, Z-score normalization — covered in Lecture 3 and Lecture 4
- Gradient Descent — iterative parameter update, learning rate, convergence — covered in Lecture 4 and Lecture 5
- Overfitting and Bias-Variance Tradeoff — memorization vs. learning, model complexity — covered in Lecture 5
- Regularization Introduction — basic concept of penalizing complexity — covered in Lecture 5
Regularization — Worked Numerical Examples
6.1 Review of Linear Regression Fundamentals
6.1.1 Hypothesis Function
The analogy breaks when inputs interact. A real recipe might need you to "mix flour and eggs before adding sugar," but linear regression just adds everything up independently. That is its strength (simplicity) and its weakness (it cannot capture interactions unless you explicitly create interaction features).
Simple Linear Regression (one input variable):
Multiple Linear Regression (more than one input variable):
Vectorized form:
Here is an matrix — each row is one training example, column 0 is all 1s (for ). is an column vector. This single matrix multiplication computes predictions for all records at once. For one record, use the scalar form.
6.1.2 Symbol Registry — Linear Regression
| Symbol | Meaning | Type | Domain |
|---|---|---|---|
| Feature (input variable) | scalar | ||
| Coefficient (parameter/weight) for feature | scalar | ||
| Intercept (bias term) — where the line crosses the Y-axis | scalar | ||
| Hypothesis function — predicted value for input | scalar | ||
| Actual target value | scalar | ||
| Number of training samples (records) | scalar | ||
| Number of features | scalar |
6.1.3 Loss Function (Cost Function)
The goal of training is to find the values that minimize .
Why the ? It cancels the 2 from the derivative of the square, keeping the gradient clean. The averages over examples so the cost does not grow with dataset size. In Bishop's standard text, the cost is written without as . The convention used here makes the gradient magnitude independent of dataset size.
6.1.4 Two Ways to Solve Linear Regression
This gives the exact minimizer in one step. Cost: for the matrix inverse — slow when the feature count is large.
Method 2 — Gradient Descent: An iterative method. Start with initial values (often zeros). Repeatedly update all simultaneously:
The partial derivative:
Full update rule:
Where is the learning rate — how big each step is.
examples, feature. Data: , . Initial: , . .
Step 1 — Predict:
Step 2 — Errors:
Step 3 — Gradients (recall always):
Step 4 — Update:
New hypothesis: . We moved toward the true line . Sense-check: the predictions improved from [2, 4] toward [5, 9].
1. Forgetting . The intercept has a "feature" that is always 1. Miss it and your gradient is wrong.
2. Not updating simultaneously. Compute ALL temps with OLD values, then update ALL at once. Never use a just-updated to compute .
3. Learning rate too large. If is too big, oscillates or diverges. Always plot vs. iteration to verify it decreases.
4. Forgetting to recompute predictions. Each iteration needs fresh predictions from the updated parameters.
6.2 Overfitting
6.2.1 Definition and Analogy
The model learns noise, not just the pattern. It memorizes each tree instead of learning where trees grow.
An overfitted model has low bias (it fits the training data perfectly) and high variance (small changes in training data would produce very different models).
6.2.2 Visual Representation
- An underfitted model is a flat horizontal line — for every input it predicts the same constant. The model is too simple; it made a completely wrong assumption about the data.
- A well-fitted model is a smooth line passing through the middle of the data cloud — capturing the trend without chasing every wiggle.
- An overfitted model is a wiggly, jagged line that twists sharply to go through every single data point. It is hypersensitive — it has found complex relationships that may not even be real.
The overfitted line looks impressive on the training plot (touches every point) but would look terrible if you plotted it against new data points from the same process.
6.2.3 Recognizing Overfitting from Coefficients
Example pattern (illustrative):
- (modest)
- (large — 18.5× the effect per unit of )
- (huge)
- (huge and negative)
These numbers are illustrative, not from a specific dataset. The pattern is what matters: large coefficients ( or ) signal that the model is twisting itself to fit noise. A well-fitted model typically has modest coefficients.
6.2.4 Consequence of Overfitting
The consequence: good training performance but bad test performance. Training error near zero with huge test error is the classic overfitting signature.
1. "My training score is perfect!" — A training of 0.99 is a red flag, not a victory. Always check test performance.
2. Adding more features blindly. Every new feature gives the model another knob to twist. Without enough data, more features = more overfitting.
3. Confusing overfitting with "the model is learning well." A model that goes through every training point has not learned — it has memorized. Learning means finding the pattern, not the points.
Real-world connection. Overfitting is not just an academic concern. In medical diagnosis, an overfitted model might learn to recognize the exact patients in the training set rather than the disease patterns — and fail catastrophically on new patients. In finance, an overfitted trading strategy looks brilliant on historical data but loses money the moment it goes live. The 2008 financial crisis was partly blamed on overfitted risk models that worked perfectly on past data but collapsed under new market conditions.
6.3 Bias and Variance
6.3.1 Definitions
The analogy breaks because in ML, you cannot simply "adjust your sight." Reducing bias usually increases variance, and vice versa. This is the bias-variance tradeoff.
| Condition | Meaning | Model State |
|---|---|---|
| High bias, low variance | Too simple, consistent but wrong | Underfitting |
| High variance, low bias | Too complex, fits noise | Overfitting |
| Low bias, low variance | Accurate and stable | Best fit |
| High bias, high variance | Wrong AND unstable | Worst case |
The goal: balance bias and variance for the lowest total error on new data.
6.3.2 Student Question
1. Confusing bias (the intercept) with bias (the error). is the intercept — it shifts the line up/down. Bias in the bias-variance sense is a type of error. Same word, completely different meaning.
2. Thinking "low bias + low variance is always achievable." There is a tradeoff. You cannot simultaneously minimize both beyond what the data and model class allow. More data helps — it pushes the tradeoff curve downward.
3. Measuring only training error. Training error conflates bias and variance. You need a separate validation/test set to disentangle them.
Real-world connection. The bias-variance tradeoff guides model selection. Google’s recommendation system chooses between a simple model (works OK for everyone) or a complex model (great for some, terrible for others). Regularization lets them tune this tradeoff with a single knob ().
6.4 Regularization — Core Concept
6.4.1 The Intuition
Regularization rewards simplicity. It is like a tax system for model complexity: you can use complex explanations (large coefficients), but you pay a penalty for doing so. The model must decide: "Is the improvement in prediction accuracy worth the complexity tax I will pay?"
The speed-limiter analogy: regularization is a governor on a car engine. The car can go fast (fit the data perfectly), but the governor limits how fast it can accelerate in any one direction (how large any one coefficient can grow). This prevents the model from "racing" to extreme coefficient values.
6.4.2 Standard Linear Regression vs. Regularized Linear Regression
Regularized linear regression: the best model balances two competing objectives:
1. Low prediction error (same as OLS)
2. Small, simple coefficients — all should be small in magnitude
The model must reduce prediction error while also keeping coefficients simple. A model with enormous coefficients that fits perfectly is penalized more than a model with modest coefficients that fits almost as well.
6.4.3 The Penalty Term — Tax Analogy
This is a tax on complexity:
- Small coefficients → small penalty → low tax. This is the desired model.
- Large coefficients → large penalty → high tax. The tax offsets the reduction in error, punishing complexity.
The parameter (lambda) is the tax rate. means no tax — we are back to OLS. Large means high tax — the model is forced toward extreme simplicity.
This creates a trade-off: the model can choose large coefficients (pay high tax) or small coefficients (pay low tax). The goal is to find the right balance where the marginal benefit of a larger coefficient equals the marginal tax cost.
6.4.4 Student Question
1. Thinking regularization "fixes everything." Regularization reduces variance but can increase bias. Too much regularization ( too large) → underfitting. You must tune .
2. Forgetting to scale features first. If one feature ranges 0–1 and another ranges 0–1000, regularization penalizes them unequally. Always scale before regularizing (Section 6.12).
3. Regularizing . The intercept should never be penalized. Penalizing forces the regression line through the origin, which is rarely appropriate.
Real-world connection. Regularization is everywhere in modern ML. Every deep learning framework includes L2 regularization ("weight decay"). In genomics with 20,000 features but only 200 samples, regularization is essential. The Lasso variant is particularly popular in bioinformatics because it automatically selects which genes matter.
6.5 Ridge Regression (L2 Regularization)
6.5.1 Definition
The speed-limiter analogy (from Section 6.4): Ridge is a proportional speed limiter. The faster you go, the harder it pushes back. A coefficient of 10 gets 5× the pushback of a coefficient of 2.
Where (lambda) is the regularization parameter — the tax rate. The sum runs from to , excluding .
In Bishop's notation (standard reference): . The factor is conventional — it cancels with the 2 from the derivative of the squared penalty.
6.5.2 The Update Rule (Gradient Descent)
The derivation: the data term differentiates exactly as in standard linear regression (Section 6.1.4). The penalty term differentiates to (the cancels the 2 from the power rule).
Plugging into the gradient descent update :
Two parts of this update:
- Shrinkage term: — multiplies the old coefficient by a factor < 1, shrinking it
- Data error term: — same gradient step as standard linear regression
> Notation note: Some alternative formulations absorb the into (writing the penalty as ), which would give shrinkage factor . The professor's worked examples (Section 6.10) use the form derived above with shrinkage factor . Both are correct under their respective conventions; the key is to be consistent.
6.5.3 How Shrinkage Works
Every iteration, each coefficient gets multiplied by 0.8 — a 20% reduction — before the data-driven gradient step is applied.
If a coefficient from OLS would have been , Ridge's multiplicative shrinkage fights it every step. The coefficient can still grow if the data error gradient pushes hard enough, but it must overcome the 20% per-iteration decay. This tug-of-war between "fit the data better" and "stay small" is exactly what prevents overfitting.
6.5.4 Key Property: Shrinks Toward Zero but Never Reaches Zero
6.5.5 When to Use Ridge Regression
When NOT to use Ridge. If you suspect many features are completely irrelevant, Ridge wastes model capacity on them. Use Lasso instead (Section 6.6), which can drive useless features to exactly zero.
6.5.6 Theta_0 Is NOT Regularized
Pitfall: When implementing Ridge, make sure your code skips in the penalty. A common bug is to regularize all parameters including the intercept.
Real-world connection. Ridge regression is the workhorse of regularized linear models. It is the default regularizer in scikit-learn's Ridge class. It is used in econometrics and any domain with correlated features, where OLS coefficients become unstable. The closed-form Ridge solution (derived in Bishop §3.1.4) shows explicitly how stabilizes the matrix inverse when is near-singular.
6.6 Lasso Regression (L1 Regularization)
6.6.1 Definition
The key difference: absolute value has a "kink" at zero. This kink is what allows Lasso to push coefficients all the way to exactly zero, while Ridge's smooth quadratic penalty only pushes toward zero asymptotically.
There are no squared terms in the penalty — it is directly proportional to the absolute coefficient values.
In Bishop's notation: the general regularizer form is . Lasso is , Ridge is . The factor of in Bishop's form is omitted here (as is common in the Lasso literature) since there is no square to cancel.
6.6.2 How the Penalty Scales
| Coefficients | Lasso penalty | Ridge penalty |
|---|---|---|
| , | ||
| , |
Ridge's quadratic penalty makes large coefficients disproportionately expensive. Lasso's linear penalty treats all coefficient increases equally. This is why Ridge shrinks big coefficients aggressively while Lasso is willing to keep some large coefficients if they reduce error enough — and eliminate small ones entirely.
6.6.3 The Update Rule
At , the derivative is not defined (the absolute value has a kink). In practice, implementations use subgradient methods to handle this.
Plugging into gradient descent:
Where is the sign of the coefficient — if , if . This is NOT the trigonometric sine function (). It is simply the plus-or-minus sign.
> Important: takes only the sign ( or ), NOT the magnitude. For , use , not .
6.6.4 Constant Change Property
Contrast with Ridge:
| Ridge (L2) | Lasso (L1) | |
|---|---|---|
| Penalty contribution to update | (depends on ) | (constant magnitude) |
| Large coefficient | Large shrinkage | Same constant push |
| Small coefficient | Small shrinkage | Same constant push |
| Zero coefficient | Zero push | Can push through zero |
Because Lasso applies the same constant force regardless of coefficient size, a small coefficient can be pushed all the way through zero. That is how Lasso eliminates features.
6.6.5 Key Property: Coefficients Can Become Exactly Zero
Why can Lasso hit zero but Ridge cannot? In Ridge, the update multiplies by . A non-zero number times a positive factor is always non-zero. In Lasso, the update subtracts a constant. If and the constant push is , the coefficient goes to , crossing zero. With subgradient methods at zero, the coefficient can stay at exactly zero.
6.6.6 When to Use Lasso Regression
When NOT to use Lasso. If all features genuinely matter (even a little), Ridge is better because Lasso might arbitrarily eliminate some correlated features. Also, when (more features than samples), Lasso selects at most features — which may be a limitation or a benefit depending on your goal.
6.6.7 Student Question — The Sign Function
A (professor's): The sign term comes from taking the derivative of the absolute value in the cost function. The derivative of is when and when .
When is negative, , so:
— the penalty is added, pushing toward zero from below.
When is positive, , so:
— the penalty is subtracted, pushing toward zero from above.
Critical detail: multiplies only by or , NOT by the magnitude of . If , the penalty contribution is , not .
6.6.8 Geometric Intuition — Overshooting
This is why feature scaling is critical for Lasso (Section 6.12). Without proper scaling, the constant may be wildly disproportionate to some coefficients, causing oscillation instead of convergence.
The geometric picture: Lasso's constant push is like taking fixed-size steps on a curved surface. If the steps are too big relative to the curvature, you overshoot the minimum and bounce between the two sides of the bowl.
Real-world connection. Lasso was introduced by Robert Tibshirani in 1996. It is used in genomics, text classification, and compressed sensing. The "selection" part of LASSO is what makes it special — it gives you an interpretable model where you can say exactly which features matter.
6.7 Elastic Net
Where is the mixing parameter (sometimes called in scikit-learn):
- → Pure Ridge (L2 only)
- → Pure Lasso (L1 only)
- → Combination of both (typical: )
The parameter controls overall penalty strength; controls the L1/L2 mix.
| Property | Ridge (L2) | Lasso (L1) | Elastic Net |
|---|---|---|---|
| Penalty form | |||
| Can zero out features? | No (approaches zero asymptotically) | Yes (exactly zero) | Yes (L1 component enables this) |
| Handles correlated features? | Yes (shares weight) | No (picks one arbitrarily) | Yes (L2 component stabilizes) |
| Feature selection? | No | Yes (automatic) | Yes (automatic) |
| Best when | All features matter | Many features are useless | Some features useless + correlations exist |
One-line rule: If you are unsure whether to use Ridge or Lasso, use Elastic Net and tune by cross-validation.
Real-world connection. Elastic Net is the safest default for production pipelines. When features are correlated, Lasso’s arbitrary selection is a real problem. Elastic Net's L2 component ensures that all correlated useful features share the weight rather than one getting everything and the rest getting zero.
6.8 The Regularization Parameter Lambda ()
6.8.1 Role
6.8.2 Effect of Different Lambda Values
| Value | Effect | Model Behavior |
|---|---|---|
| No penalty | Pure OLS. Regularization is off. Prone to overfitting. | |
| very small (e.g., ) | Tiny penalty | ~99% of each retained per iteration. Behaves almost like OLS. |
| moderate (e.g., –) | Balanced penalty | Good tradeoff: fits the data well while keeping coefficients modest. |
| large (e.g., –) | Strong penalty | Most coefficients near zero. Model approaches a horizontal line (just ). |
| Infinite penalty | All for . Model = = mean of . Complete underfitting. |
6.8.3 How to Choose Lambda
1. Try a range of values on a log scale: .
2. Use cross-validation (Section 6.14): for each , train on part of the data, evaluate on the held-out part. Pick the with the lowest average validation error.
3. GridSearchCV in scikit-learn automates this: it tries all combinations and returns the best.
The "one standard error" rule: sometimes you pick a slightly larger (simpler model) whose error is within one standard error of the minimum — this gives a more parsimonious model with essentially the same performance.
1. Searching on a linear scale. misses the important small values. Always search on a log scale: .
2. Using test data to choose . If you pick based on test performance, your test error is now biased (you "peeked"). Use a separate validation set or cross-validation.
3. Assuming one works everywhere. Different datasets need different . Never hardcode a value from one project into another.
Real-world connection. In practice, selection is done automatically. The key skill is understanding the log-scale search and U-shaped validation curve. When a model performs poorly, varying and plotting the validation curve is one of the first diagnostic steps — it tells you whether regularization strength is the problem.
6.9 Worked Example — Simple Gradient Descent (1 Iteration)
6.9.1 Problem Setup
Given parameters:
- (learning rate)
- (intercept)
- (coefficient for BMI)
- (coefficient for diastolic pressure)
- (three patients)
Hypothesis function:
6.9.2 Iteration 1 — Step-by-Step
The three patients have the following data (reconstructed from the lecture context):
| Patient | (BMI) | (Diastolic BP) | (CHD risk) |
|---|---|---|---|
| 1 | 35 | 80 | 1.81 |
| 2 | 32 | 90 | 1.95 |
| 3 | 30 | 100 | 2.10 |
Patient 1:
Patient 2:
Patient 3:
Step 2: Compute error for each patient.
| Patient | error | ||
|---|---|---|---|
| 1 | 1.55 | 1.81 | |
| 2 | 1.34 | 1.95 | |
| 3 | 1.10 | 2.10 |
All errors are negative — the model is underpredicting for all three patients.
Step 3: Compute the gradient (temp values).
For — recall that for all examples (the intercept feature):
For :
For :
Step 4: Update parameters.
After iteration 1, the updated hypothesis is:
Sense-check: The coefficients and jumped from to and — a huge change in one iteration. This is because the data is NOT scaled (BMI ~30, BP ~100, but target ~2). The unscaled features produce enormous gradients (, ). This is a preview of why feature scaling (Section 6.12) is essential.
6.9.3 Going to Iteration 2 (Conceptual)
Each iteration is a fresh calculation: predict → error → gradient → update → repeat.
6.10 Worked Example — Ridge Regression (2 Iterations)
6.10.1 Setup
Additional given:
- (regularization constant)
- (unchanged)
- Apply Ridge update rule for 2 iterations
6.10.2 Computing the Shrinkage Factor
This factor is constant across iterations — it depends only on and , not on or the data. Every iteration, each coefficient (for ) is multiplied by — a 10% reduction — before the data-driven gradient step.
> Formula reconciliation: The professor's general notation in Section 6.5.2 shows shrinkage as . However, the worked example here computes without dividing by . This is the correct form given the cost function , where . The update becomes . The worked example below follows this correct derivation. If an alternative convention is used where the penalty is written as , then the shrinkage would be . Always verify which convention your code or library uses.
6.10.3 Iteration 1
Step 2 — Errors (same as Section 6.9):
Step 3 — Gradients (same temp values as Section 6.9):
Step 4 — Ridge updates:
- is NOT regularized — standard update:
- (shrinkage factor 0.9 applied):
- (same structure):
Compare with simple LR (Section 6.9): Ridge's vs. simple LR's . The shrinkage factor pushed to before the gradient step, making the final value slightly larger. Ridge and simple LR already differ after one iteration.
6.10.4 Iteration 2
Using , , :
The predictions are absurdly large (~109–130) when the actual target values are ~1.8–2.1. This happens because the data is NOT scaled — the features (BMI ~30, BP ~100) interact with the now-large coefficients to produce huge predictions.
Step 2 — Compute new errors:
Step 3 — Compute new gradients:
Step 4 — Ridge updates for iteration 2:
After two iterations, the coefficients are wildly unstable — , . The model has blown up.
6.10.5 Important Observations
1. Feature scales differ by orders of magnitude. BMI ~30 vs. BP ~100 vs. target ~2. The gradients for and are enormous ( and in iteration 1) compared to the coefficients themselves ().
2. The learning rate is too large for unscaled data. multiplied by temp values of thousands (iteration 2) produces coefficient jumps of hundreds.
3. Ridge's shrinkage (0.9) is negligible against these gradient magnitudes. A 10% reduction on a coefficient cannot compensate for a data-gradient update of .
The lesson: These bad results are NOT Ridge's fault. They are the data's fault. Always scale features before applying gradient descent with or without regularization (Section 6.12).
6.11 Worked Example — Lasso Regression (2 Iterations)
6.11.1 Setup
6.11.2 Computing the Constant Penalty Term
This constant is the amount added or subtracted in each iteration (the sign depends on ). Unlike Ridge, this does NOT depend on the magnitude of — it is the same push whether or .
6.11.3 Iteration 1
Since both coefficients are negative, . The penalty term:
The penalty is added (pushing the negative coefficients toward zero from below).
update: No regularization, same as simple LR (Section 6.9):
update:
Notice: the penalty pushed this coefficient further positive. Combined with the large data gradient (), jumped from to — crossing zero and flipping sign in ONE iteration. This is the overshooting phenomenon (Section 6.6.8).
update:
Both coefficients have become positive (from negative) after one iteration. The constant penalty, combined with the large positive data gradients from unscaled features, caused the coefficients to jump far past zero.
6.11.4 Iteration 2
Predictions are very large (~120–143 vs. actual ~2) — same scaling problem as Ridge.
Step 2 — Compute new errors:
Step 3 — Now the coefficients are positive, so . The penalty term flips:
The penalty is now subtracted — pulling the positive coefficients back toward zero.
Step 4 — Lasso updates for iteration 2 (using recomputed temp values):
The penalty flips from to because the coefficients flipped from negative to positive. This alternation — adding the penalty when coefficients are negative, subtracting when positive — can cause oscillation if is large relative to the data gradient. The coefficients bounce back and forth across zero instead of converging.
With unscaled data producing enormous gradients (temp values of thousands), the penalty is negligible. The coefficients are driven by the data error, not the regularization.
6.11.5 Comparison — Ridge vs Lasso vs Simple LR After Iterations
| Method | Update mechanism | Iteration 1 | Behavior |
|---|---|---|---|
| Simple LR | Data gradient only | Fast, no regularization | |
| Ridge | + data gradient | Slightly different from LR | |
| Lasso | + data gradient | Jumped past zero (overshoot) |
The values are not ideal for any method because the dataset is unscaled. But the computation process is what matters:
- Simple LR: updates from data error gradient only.
- Ridge: multiplicative shrinkage on each coefficient BEFORE the data gradient.
- Lasso: constant additive/subtractive penalty , with sign determined by .
6.11.6 Student Question
A (professor's): Substitute the value into the hypothesis function and evaluate. A negative means: as increases by one unit, the predicted decreases by units (assuming stays fixed).
In the hiker analogy (Section 6.1.4): a negative slope means the hiker is on the left side of the bowl. To reach the minimum at the bottom, they must move right (increase the parameter). The sign tells you which direction to walk.
6.12 Data Preprocessing and Feature Scaling
6.12.1 Why Scaling Matters
In the CHD example: BMI ranges ~25–35, diastolic BP ranges ~80–100, but the target ranges ~1.8–2.1. The cost function becomes a long, narrow valley instead of a nice round bowl. Gradient updates for (BP) are ~3× larger than for (BMI) purely because of scale, not because BP matters more.
6.12.2 Standard Scaler
Where:
- = mean of feature across all training examples
- = standard deviation of feature across all training examples
After scaling, every feature has:
- Mean = 0
- Standard deviation = 1
This puts ALL features on the same scale, so gradient descent can take balanced steps in every direction. The cost function becomes a nice round bowl instead of a stretched valley.
BMI: ,
- Patient 1:
- Patient 3:
Diastolic BP: ,
- Patient 1:
- Patient 3:
After scaling, both features range roughly to , and the gradients would be balanced. The Ridge and Lasso updates would behave properly.
6.12.3 Garbage In, Garbage Out
If data preprocessing is neglected, no model — Ridge, Lasso, Elastic Net, or anything else — will produce meaningful results. The wild coefficient values in Sections 6.9–6.11 are not the model's fault; they are the data's fault.
When your model gives strange results, check preprocessing first:
1. Are features on wildly different scales? → Use StandardScaler.
2. Are there missing values? → Impute (mean, median, or mode).
3. Are categorical variables encoded? → One-hot or label encoding.
4. Are there outliers? → Consider clipping or robust scaling.
6.12.4 Feature Engineering
- Scaling: StandardScaler, MinMaxScaler, RobustScaler
- Missing value handling: imputation with mean, median, mode, or model-based
- Encoding: one-hot encoding for nominal categories, label/ordinal encoding for ordered categories
- Feature creation: polynomial features, interaction terms, domain-specific transformations
- Feature selection: choosing which features to include (or letting Lasso do it)
Feature engineering is often more important than model choice. A simple linear regression on well-engineered features can outperform a deep neural network on raw data.
Real-world connection. In industry, data preprocessing consumes 60–80% of a data scientist's time. Google’s first rule: "Make sure your pipeline is solid end-to-end."
6.13 ML Pipelines and Model Deployment
6.13.1 scikit-learn Pipelines
fit() once and it handles everything in sequence.
Inputs & Outputs. Input: raw training data . Output: a trained model ready for predictions, with all preprocessing parameters (means, standard deviations, imputation values) baked in.
Steps:
1. Missing value imputation — fill gaps using median, mean, or mode (SimpleImputer)
2. Feature scaling — transform features to mean 0, std 1 (StandardScaler)
3. Model training — fit the chosen model (LinearRegression, Ridge, Lasso)
`
Preprocessor: SimpleImputer(strategy='median') → StandardScaler()
Full Pipeline: Preprocessor → Ridge(alpha=lambda_value)
A single pipeline.fit(X_train, y_train) runs imputation → scaling → model fitting. A single pipeline.predict(X_test)` runs the same transformations then predicts.
``python
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
pipeline = Pipeline([
('imputer', SimpleImputer(strategy='median')),
('scaler', StandardScaler()),
('model', Ridge(alpha=1.0))
])
# One call does everything
pipeline.fit(X_train, y_train)
predictions = pipeline.predict(X_test)
`
The pipeline stores the median of each feature (from training data) and the mean/std of each feature (from training data). These are used during predict()` — you never recompute them on test data.
transform() uses the parameters learned during fit(). If you manually scale, a common bug is computing and on the combined train+test data, which leaks information from the test set into training.
6.13.2 Joblib — Saving Trained Models
.pkl (pickle) or .joblib format. This lets you train once and reuse the model later without retraining.
``python
import joblib
joblib.dump(pipeline, 'model.joblib') # save
loaded_model = joblib.load('model.joblib') # load later
6.13.3 Streamlit — Web App Deployment
- Load a saved model (using joblib)
- Create input widgets (sliders, text boxes, number inputs)
- Run predictions on user-provided values
- Display results with charts and metrics
- Deploy to Streamlit Cloud or run locally
A Streamlit app can include interactive sliders for hyperparameters like , letting users adjust regularization strength and see the effect on predictions in real time.
6.13.4 The Fit-Train-Predict Workflow
1. Fit — Train the model on training data: model.fit(X_train, y_train)
2. Predict — Make predictions on test data: model.predict(X_test)
3. Evaluate — Compare predictions to actual values using metrics (MSE, RMSE, )
Never evaluate on training data (that gives an overoptimistic estimate). Never use test data during fit() (that leaks information).
6.13.5 Assignment Guidance — Pipelines
A (professor's): No. Use standard function calls, not pipelines. The assignment is designed to build foundational understanding by implementing steps manually. Pipelines will be covered in a future webinar. However, after completing what is asked, you are free to try additional models (including decision trees) and include them as extra submissions.
fit()/predict() interface. Joblib saves trained models. Streamlit deploys them as web apps. For the assignment: implement manually first, then experiment. Next: automated hyperparameter tuning (Section 6.14).
Real-world connection. ML pipelines are the backbone of production ML. Kubeflow, MLflow, and SageMaker extend the scikit-learn Pipeline concept. The principle is always the same: preprocessing and model must travel together as one unit.
6.14 Hyperparameter Tuning and Grid Search
6.14.1 GridSearchCV
GridSearchCV is a scikit-learn class that automatically tries multiple combinations of hyperparameters (like and ) and finds the combination with the best cross-validated performance.
Inputs & Outputs. Input: a model (or pipeline), a parameter grid (dictionary of parameter names → lists of values to try), and the training data. Output: the best parameter combination and the best trained model, ready for prediction.
Steps:
1. Define the parameter grid. Example: {'alpha': [0.001, 0.01, 0.1, 1, 10]} for Ridge.
2. For each parameter combination, perform cross-validation:
- Split training data into folds
- Train on folds, validate on the held-out fold
- Repeat times, average the score
3. Select the combination with the highest average validation score.
4. Retrain the final model on ALL training data using the best parameters.
``python
from sklearn.linear_model import Ridge
from sklearn.model_selection import GridSearchCV
param_grid = {'alpha': [0.001, 0.01, 0.1, 1, 10, 100]}
grid = GridSearchCV(Ridge(), param_grid, cv=5, scoring='neg_mean_squared_error')
grid.fit(X_train, y_train)
print(grid.best_params_) # e.g., {'alpha': 0.1}
``
6.14.2 Cross-Validation
- Split data into 5 equal parts (5-fold CV)
- Train on folds 1–4, test on fold 5 → score₁
- Train on folds 1–3,5, test on fold 4 → score₂
- …repeat 5 times…
- Final score = average of score₁ through score₅
This gives a more reliable estimate than a single train/test split because every example gets used for both training and validation. The downside: 5× the training time.
6.14.3 Assignment Guidance — Grid Search
A (professor's): After completing what is asked in the assignment, you can try any additional methods — including Grid Search, existing library functions, or even decision trees. Include everything in your submission. The more you try, the better.
1. Grid search on test data. Never pass X_test to GridSearchCV.fit(). The grid search uses cross-validation on the TRAINING data only. Using test data for parameter tuning defeats the purpose of having a test set.
2. Too fine a grid. Trying 100 values of × 100 values of × 10 folds = 100,000 model fits. Use a coarse grid first, then refine around the best region.
3. Forgetting to set the random seed. Without random_state, different runs give different CV splits and potentially different "best" parameters.
6.15 Student Q&A — Model Performance Issues
A (professor's): This gap — low training error, high test error — is the classic overfitting signature. The model has memorized the training data instead of learning the pattern. To fix it:
1. Tune hyperparameters — adjust (learning rate) and (regularization strength). Try different values. Larger = stronger penalty = simpler model = less overfitting.
2. Feature engineering — ensure all features are properly scaled, missing values are handled, and the right features are selected. Unscaled data can cause wildly different training and test errors, as shown in Sections 6.9–6.11.
3. Data cleaning — check for outliers, inconsistencies, and scaling issues. One bad outlier can inflate test error dramatically.
4. Get more data — if possible, more training examples reduce overfitting. Regularization is especially important when data is limited.
5. Simplify the model — use fewer features or a simpler model class (e.g., linear instead of polynomial).
The key takeaway: feature engineering is extremely important. As demonstrated in the worked examples, unscaled data can produce wildly different training and test errors.
A (professor's): Only the final preprocessed columns should be fed to the model. Keep a copy of the original CSV for reference, but the model must only see cleaned, scaled data. Do not leave unclean data in the input — it will cause problems. Specifically:
- If you scaled a column, use ONLY the scaled version, not the original.
- If you one-hot encoded a categorical column, use ONLY the encoded columns, not the original.
- Never mix raw and processed versions of the same feature — that creates redundancy and confuses the model.
6.16 Gradient Descent — Contour Plot Visualization
6.16.1 The Convex Bowl
Now view the bowl from directly above. You see concentric ellipses — contour lines. Each ellipse connects points with the same cost. The innermost ellipse (the smallest one, often just a dot) is the global minimum. Gradient descent's path on the contour plot is a trail of dots spiraling inward toward that center.
6.16.2 How the Line Changes
Left plot (data space): Scatter of training points . A regression line drawn through them.
Right plot (parameter space / contour): Contour ellipses of . A point marks the current .
- Each point on the contour plot corresponds to a different line on the data plot.
- At the start (iteration 0), the line on the left is far from the data points. The point on the right is far from the contour center.
- Each gradient descent update moves the point on the right closer to the center. Simultaneously, the line on the left shifts and rotates toward the best fit.
- At convergence (innermost contour), the line on the left fits the data optimally.
Axes: The contour plot has on one axis and on the other. The data plot has on the horizontal and on the vertical.
6.16.3 Using the Same Concept for Regularization
1. The slope of the data error surface — how much does prediction error change when I adjust ?
2. The slope of the penalty surface — how much does the penalty change when I adjust ?
The hiker combines both slopes into one step. The penalty surface is a simple bowl centered at the origin (minimum penalty when all ). The data error surface is centered wherever the OLS solution is. Regularized gradient descent finds a compromise point between these two minima — closer to OLS when is small, closer to the origin when is large.
In Bishop's visualization (Figure 3.4), the unregularized error contours (blue ellipses) are overlaid with the constraint region (red circle for Ridge, diamond for Lasso). The solution is where the smallest error contour just touches the constraint region. For Lasso, this touch point often lies on an axis — meaning some .
6.17 Connection to Logistic Regression
6.17.1 Same Penalty Concept, Different Cost Function
- Ridge penalty for logistic regression: Add to the log-loss cost.
- Lasso penalty for logistic regression: Add to the log-loss cost.
- Elastic Net for logistic regression: Add the mixed L1/L2 penalty.
The intention is unchanged: keep coefficients small and simple. The only difference is the data-error term — log loss instead of MSE. The gradient of the penalty (and thus the shrinkage/constant-push behavior) is identical.
In scikit-learn: LogisticRegression(penalty='l2', C=1/lambda) for Ridge-regularized logistic regression. The parameter C is the inverse of — . So small C = strong regularization. This is a common source of confusion.
6.17.2 Why This Topic Matters
Real-world connection. In scikit-learn, LogisticRegression is regularized by DEFAULT (L2 penalty, C=1.0). This is a design choice reflecting the practical reality that unregularized logistic regression is almost never the right choice — just like in linear regression, regularization is the safe default.
6.18 Assignment Guidance Summary
6.18.1 Submission
- Only one submission is allowed on the learning platform — make it count.
- Use standard function calls (not ML pipelines) for the assignment. Build understanding by implementing steps manually.
- After completing the required tasks, try additional models and methods (decision trees, GridSearchCV, different regularizers) and include them as extra work. The more you experiment, the better.
6.18.2 Grading
6.18.3 Key Advice
1. Feature engineering is critical — properly scale, clean, and select features. This is often the difference between a mediocre model and a great one.
2. Hyperparameter tuning (, ) can significantly improve results. Try multiple values.
3. Try multiple models — Ridge, Lasso, Elastic Net, simple linear regression — and include everything in your submission.
4. After the assignment, discuss results with peers. Different approaches lead to different insights.
6.19 Key Industry Applications and Tools
| Tool / Concept | Purpose | Used In |
|---|---|---|
| scikit-learn | Python ML library — provides LinearRegression, Ridge, Lasso, ElasticNet, Pipeline, GridSearchCV, StandardScaler | Industry standard for classical ML; used by Spotify, Airbnb, JPMorgan |
| Joblib | Model serialization — save/load trained models in .pkl or .joblib format | Production deployment; part of the scikit-learn ecosystem |
| Streamlit | Python framework for building ML web apps with minimal code (no HTML/CSS needed) | Rapid prototyping, internal tools, demos; used by Uber, Delta, Snowflake |
| Streamlit Cloud | One-click deployment of Streamlit apps | Sharing models with non-technical stakeholders |
| GridSearchCV | Automated hyperparameter tuning with cross-validation | Model selection in every ML project |
| Cross-validation | Evaluating model performance by training on multiple data splits | Reliable performance estimation; standard in academic papers and industry |
| StandardScaler | Feature scaling — transforms features to mean 0, standard deviation 1 | Preprocessing step in virtually every regression pipeline |
| ML Pipelines | Chaining preprocessing and modeling steps for production | Prevents train-test leakage; enables one-click retraining |
| Decision Trees | Alternative non-linear model type | Baseline comparison; interpretable models for regulated industries |
- Healthcare/epidemiology: Predicting disease risk from patient biomarkers. Lasso selects which biomarkers matter from thousands of candidates.
- Finance: Credit scoring, fraud detection, portfolio optimization. Ridge stabilizes models when economic indicators are highly correlated.
- Marketing: Customer lifetime value prediction, churn modeling. Elastic Net handles the mix of useful and useless features in CRM data.
- Genomics/Bioinformatics: GWAS (Genome-Wide Association Studies) use Lasso to identify which genes are associated with a disease from tens of thousands of candidates.
- Real estate (Zillow Zestimate): Regularized regression on hundreds of property features to predict home values.
The tools above form the standard Python ML stack. Virtually every data scientist uses scikit-learn + joblib + some deployment framework (Streamlit, Flask, FastAPI) as their daily toolkit.
6.20 Key Formulas Reference
This section collects all key formulas from the lecture in one place for quick reference and exam revision.
Standard Linear Regression
Hypothesis:
Cost function (MSE):
Gradient descent update (for ):
Closed-form (Normal Equation):
Ridge Regression (L2)
Cost function:
Gradient descent update (for ):
For (NOT regularized): Same as standard linear regression update.
Closed-form (Ridge):
where is the identity matrix with (to exclude from penalty).
Lasso Regression (L1)
Cost function:
Gradient descent update (for , ):
where if , if .
Elastic Net
Penalty:
- → Pure Ridge
- → Pure Lasso
- → Mixed
Feature Scaling
Standardization (Z-score):
where = mean, = standard deviation of the feature (computed on training data only).
Quick Decision Guide
| Situation | Method |
|---|---|
| All features matter, data is clean | Ridge (L2) |
| Many features, some are noise | Lasso (L1) |
| Unsure, or features are correlated | Elastic Net |
| unknown | GridSearchCV with cross-validation |
| Raw data, different scales | StandardScaler FIRST |
ML Lecture 6 notes · Regularization — Worked Numerical Examples
Sections Breakdown
Hypothesis function, cost function (MSE), closed-form solution (Normal Equation), and gradient descent update rule.
Definition, visual representation, recognizing overfitting from large coefficients, consequences.
Bias-variance tradeoff definitions, the four conditions (high/low bias/variance).
Intuition, standard vs regularized regression, penalty term as tax on complexity.
Definition, cost function, gradient descent update rule with shrinkage factor.
Definition, cost function, constant push update rule, automatic feature selection.
Combined L1 + L2 penalty, mixing parameter R, comparison of all three regularizers.
Role of lambda, effect of different values, how to choose via cross-validation.
One full iteration of gradient descent on CHD dataset.
Two iterations of Ridge gradient descent showing shrinkage factor effect.
Two iterations of Lasso gradient descent showing constant push behavior.
Why scaling matters, StandardScaler (Z-score), feature engineering overview.
scikit-learn Pipelines, Joblib model serialization, Streamlit apps.
GridSearchCV, cross-validation procedure, common pitfalls.
Diagnosing overfitting, feature engineering advice, data preprocessing.
Convex bowl analogy, contour plots, regularization effect on the minimum.
Same penalty concept applies, weight decay in neural networks.
Submission rules, relative grading, key advice for the assignment.
scikit-learn, Joblib, Streamlit, real-world applications.
Consolidated formulas for linear regression, Ridge, Lasso, Elastic Net.
Exam Revision Notes
Below is the distilled, exam-ready core of this lecture. Every entry is built from the full textbook notes above. Use this section for rapid review — but if something doesn't make sense, go back to the full explanation in the main content.
Linear Regression Fundamentals
Must-know: The hypothesis function is . The cost function is Mean Squared Error (MSE). Gradient descent iteratively updates parameters.
⚠️ Top pitfall: Forgetting the intercept feature in gradient computation. Always compute ALL temps with old values before updating simultaneously.
Self-check: What is the difference between the closed-form (Normal Equation) solution and gradient descent?
Connects to: Gradient Descent, Cost Function
Overfitting
Must-know: Overfitting = low training error + high test error + large-magnitude coefficients. The model memorizes noise instead of learning the true pattern.
⚠️ Top pitfall: Celebrating a perfect training score () without checking test performance. A perfect training fit is a red flag, not a victory.
Self-check: What pattern in coefficient values signals overfitting in linear regression?
Connects to: Bias-Variance Tradeoff, Regularization
Bias and Variance
Must-know: High bias = underfitting (too simple). High variance = overfitting (too complex). The ideal is low bias AND low variance.
⚠️ Top pitfall: Confusing the intercept term (called 'bias term') with bias in the bias-variance sense. They are completely different concepts.
Self-check: What model state corresponds to 'high bias, low variance'?
Connects to: Overfitting, Regularization
Regularization Core Concept
Must-know: Regularization adds a penalty term to the cost function. It is a tax on complexity — large coefficients are punished.
⚠️ Top pitfall: Regularizing (the intercept). The intercept should never be penalized.
Self-check: What happens when ? What happens when ?
Connects to: Ridge Regression, Lasso Regression, Elastic Net
Ridge Regression (L2)
Must-know: Ridge adds to the cost. It shrinks coefficients multiplicatively by each iteration but never reaches exactly zero.
⚠️ Top pitfall: Applying Ridge without feature scaling. Unscaled features create disproportionate gradients, rendering regularization ineffective.
Self-check: Why can Ridge never drive a coefficient to exactly zero?
Connects to: Lasso Regression, Elastic Net, Feature Scaling
Lasso Regression (L1)
Must-know: Lasso adds to the cost. It applies a constant push regardless of coefficient size, driving coefficients to exactly zero (automatic feature selection).
⚠️ Top pitfall: Lasso can overshoot zero when is too large relative to the data gradient, causing oscillation. Feature scaling is critical.
Self-check: How does the sign function determine whether the Lasso penalty adds or subtracts?
Connects to: Ridge Regression, Elastic Net, Feature Scaling
Elastic Net
Must-know: Elastic Net = Ridge + Lasso. Combines L1 feature selection with L2 stability for correlated features.
⚠️ Top pitfall: Elastic Net has TWO hyperparameters ( and ) — double the grid search space. Start coarse, then refine.
Self-check: What value of gives pure Ridge? What value gives pure Lasso?
Connects to: Ridge Regression, Lasso Regression, Hyperparameter Tuning
The Regularization Parameter
Must-know: controls penalty strength. = OLS (overfitting risk). too large = underfitting. Tune via cross-validation on a log scale.
⚠️ Top pitfall: Searching on a linear scale (1, 2, 3, ...) misses important small values. Always search on a log scale.
Self-check: What shape does the validation error curve have when plotted against log()?
Connects to: GridSearchCV, Cross-Validation, Ridge Regression
Feature Scaling and Data Preprocessing
Must-know: StandardScaler (Z-score) transforms each feature to mean 0, std 1. Always scale before regularization.
⚠️ Top pitfall: Computing and on the full dataset (train + test) instead of only on training data. This leaks test information.
Self-check: What happens to gradient descent when features have very different scales?
Connects to: Gradient Descent, Ridge Regression, Lasso Regression
Hyperparameter Tuning with GridSearchCV
Must-know: GridSearchCV automates hyperparameter search via cross-validation. Define a parameter grid, it tries all combinations and returns the best model.
⚠️ Top pitfall: Using test data for parameter tuning — this leaks information. GridSearchCV must use only training data with cross-validation.
Self-check: What is the 'one standard error' rule for choosing ?
Connects to: Cross-Validation, Regularization
Was this lecture useful?
BitsNotes AI Assistant
Subject Notes AssistantConfigure AI Chat
Choose how to access the chatbotSigned in as
Powered by BitsNotes — 20 messages per day. No API key needed. Want unlimited access? Use "Bring Your Own Key" mode.
Sign in to use AI Chat
Get 20 free AI messages per day to ask questions about your lecture notes. Sign in with Google or GitHub — it takes 5 seconds.
Sign In to BitsNotesSwitch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.