Skip to main content
Machine Learning

Regularization — Worked Numerical Examples

📅 Published: 2026-06-29
🎓 Level: postgraduate
👥 Audience: Postgraduate students in Machine Learning

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

About this lecture. This lecture covers why models overfit, the bias-variance tradeoff, and how Ridge (L2), Lasso (L1), and Elastic Net regularization prevent overfitting by penalizing large coefficients. The lecture includes fully worked gradient descent examples with and without regularization, and practical guidance on feature scaling, hyperparameter tuning, and model deployment.

6.1 Review of Linear Regression Fundamentals

Hook. If you had to predict a house's price from just its square footage, what would you do? Draw a straight line through the data points — that is linear regression. But what makes one line "better" than another? And how do we find the best one without guessing?

6.1.1 Hypothesis Function

Intuition + Analogy. Think of the hypothesis function as a recipe. Your ingredients are the input variables (like BMI, blood pressure). The recipe tells you how much of each ingredient to use (the coefficients ) and adds a fixed base amount (, the intercept). The output is your prediction — the dish.

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).

The hypothesis function is the equation the model uses to make predictions.

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

SymbolMeaningTypeDomain
Feature (input variable)scalar
Coefficient (parameter/weight) for feature scalar
Intercept (bias term) — where the line crosses the Y-axisscalar
Hypothesis function — predicted value for input scalar
Actual target valuescalar
Number of training samples (records)scalar
Number of featuresscalar
The intercept is sometimes called the bias term — do not confuse this with the "bias" in the bias-variance tradeoff (Section 6.3). They are completely different concepts that share the same English word.

6.1.3 Loss Function (Cost Function)

The loss function (or cost function) for linear regression is the Mean Squared Error (MSE):

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

Method 1 — Closed-Form Solution (Normal Equation): A direct, one-shot solution:

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.

Hiker analogy (professor's): Gradient descent is like a blindfolded hiker climbing down a mountain. The hiker feels the slope underfoot in all directions and takes a step in the steepest downhill direction. is the step size. Too small: you inch down forever. Too large: you leap over the valley and land on the opposite slope. The goal is the lowest point — the minimum of the cost function.
Tiny worked example — one gradient descent step.

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].

Pitfalls.

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.

Recap. Linear regression predicts a continuous value as a weighted sum of inputs plus an intercept. Gradient descent iteratively improves weights by moving opposite to the MSE gradient. Next: what happens when the model tries too hard — overfitting (Section 6.2).

6.2 Overfitting

Hook. Imagine studying for an exam by memorizing every answer word-for-word from the sample paper. You score 100% on the sample. Then the exam has slightly different questions — and you fail. That is exactly what happens when a machine learning model overfits.

6.2.1 Definition and Analogy

Intuition + Analogy (professor's). A set of sample questions and answers is given to students. Some students memorize every question-answer pair without understanding the concepts. If the exam uses the exact same questions, they score 100/100. But if even one question changes, they fail. Instead of understanding the data, they memorized it. That is overfitting.

The model learns noise, not just the pattern. It memorizes each tree instead of learning where trees grow.

Overfitting happens when a model learns the training data too well — it captures noise and random fluctuations alongside the true pattern. The model performs extremely well on training data but fails on new, unseen data.

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

Visual intuition. Picture a scatter plot with on the horizontal axis and on the vertical axis.

- 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

In linear regression, overfitting shows up as large-magnitude coefficients. The parameter values become extremely large (positive or negative).

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

Assumptions & Scope. Overfitting is most dangerous when: - The number of features is large relative to the number of training examples . - The data contains noise (which real data always does). - The model is highly flexible (e.g., high-degree polynomials).

The consequence: good training performance but bad test performance. Training error near zero with huge test error is the classic overfitting signature.

Pitfalls.

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.

Recap. Overfitting is memorization without understanding — low training error, high test error, large coefficients. The fix: regularization (Sections 6.4–6.11) and more data. Next: the formal framework for understanding this tradeoff — bias and variance (Section 6.3).

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

Hook. You have two archers. Archer A always hits the same spot — but it is two feet left of the bullseye. Archer B's arrows scatter all over the target, sometimes hitting the bullseye, sometimes missing entirely. Who is better? This is the bias-variance dilemma.

6.3.1 Definitions

Intuition + Analogy. Think of bias as systematic error — the archer whose sight is misaligned. Every shot clusters in the wrong place. Think of variance as scatter — the shaky archer whose arrows spray everywhere. A good model, like a good archer, needs both: aim at the right spot (low bias) AND hold steady (low variance).

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.

- Bias (in the bias-variance sense — NOT the intercept term ): Error from wrong assumptions in the model. High bias = underfitting. The model is too simple. Example: predicting for every input regardless of the features. - Variance: Error from excessive sensitivity to the training data. High variance = overfitting. The model changes dramatically if you give it slightly different training data. It chases every data point, including noise.
ConditionMeaningModel State
High bias, low varianceToo simple, consistent but wrongUnderfitting
High variance, low biasToo complex, fits noiseOverfitting
Low bias, low varianceAccurate and stableBest fit
High bias, high varianceWrong AND unstableWorst case

The goal: balance bias and variance for the lowest total error on new data.

6.3.2 Student Question

Q: Low bias and low variance is the best fit? A: Yes. High bias means underfitted — the model is too simple and misses the pattern. High variance means overfitted — the model is too jumpy and chases noise. The ideal is low bias AND low variance — accurate predictions that stay stable across different training samples.
Assumptions & Scope. The bias-variance decomposition assumes the loss is squared error. Under other loss functions (absolute error, 0-1 loss), the decomposition takes different forms. Also, this framework applies most cleanly to regression; for classification, the decomposition is more nuanced. The key practical takeaway holds regardless: too-simple models underfit, too-complex models overfit.
Pitfalls.

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.

Recap. Bias = error from oversimplification (underfitting). Variance = error from oversensitivity (overfitting). The sweet spot balances both. Next: how regularization forces the model toward that sweet spot by penalizing complexity (Section 6.4).

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

Hook. What if you could tell your model: "Yes, fit the data well — but do it as simply as possible"? That instruction is the essence of regularization. It is the difference between a student who memorizes answers and one who finds the simplest explanation that still works.

6.4.1 The Intuition

Intuition + Analogy (professor's, extended). Earlier (Section 6.2), students memorized question-answer pairs and overfit. Now the instruction changes: "I do not want you to just get the right answers. I want you to find the simplest possible explanation for these questions."

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

Standard linear regression (Ordinary Least Squares / OLS): the best model is the one with the lowest sum of squared residuals. The model does not care how it achieved that low error. Whether it reduced error by inflating coefficients dramatically or by genuinely fitting the pattern — nobody cares. The only objective is: minimize prediction error.

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

Regularization adds a penalty term to the cost function:

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

Q: How do we know when coefficients are going to be large? A: We do not know the exact threshold for "large." Anything that makes the model unnecessarily complex — that is "large." We cannot pre-define what "large" means, so in practice we apply regularization preventively. We do not wait to see if coefficients become large; we apply Ridge or Lasso from the start as insurance against overfitting. The regularization parameter is tuned by cross-validation (Section 6.14) to find the right penalty strength automatically.
Assumptions & Scope. Regularization assumes that, all else being equal, simpler models generalize better — this is Occam's razor. This holds for most problems but fails when the true relationship needs large coefficients. That is why scaling matters. Regularization also assumes you have enough data that the penalty does not overwhelm the signal.
Pitfalls.

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.

Recap. Regularization = prediction error + penalty on coefficient size. It is a tax on complexity that prevents overfitting by forcing the model to keep coefficients small. Next: the two main types of penalty — Ridge (L2) squares the coefficients, Lasso (L1) takes their absolute values (Sections 6.5–6.6).

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)

Hook. What if you could shrink every coefficient toward zero — gently, never killing any feature entirely, just dialing down the influence of each one? That is Ridge regression. It is the "everyone gets a say, but nobody shouts" regularizer.

6.5.1 Definition

Intuition + Analogy. Imagine a committee where every member gets a vote, but the chairperson can turn down the volume on loud voices. Ridge regression is that chairperson. Every feature keeps its coefficient, but Ridge squares each coefficient and adds the sum to the cost — so large coefficients get disproportionately punished (squaring makes hurt far more than ).

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.

Ridge Regression adds a penalty equal to the sum of squared coefficients (the L2 norm). The cost function:

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)

Taking the derivative of the Ridge cost function with respect to (for ):

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

Concrete example. Suppose , . Then the shrinkage factor is:

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

Ridge regression forces all coefficients toward zero, but they never become exactly zero in finite iterations. Why? The update is multiplicative: . Multiplying a non-zero number by a positive factor repeatedly approaches zero asymptotically but never hits it. A coefficient of exactly zero means that feature is eliminated. Ridge does not eliminate features — it keeps all of them but dampens their effect.

6.5.5 When to Use Ridge Regression

When to use Ridge. Use Ridge when you believe all features contribute something — even if only a tiny bit. With 100 features where each has at least a minimal relationship to the output, Ridge is the right choice. It keeps every feature, just shrinks their influence proportionally.

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

(the intercept) is excluded from the penalty sum — the sum runs from to , not . Why? The intercept decides the baseline level of predictions. Penalizing it would force the regression line through the origin , which is rarely correct. If you centered your data (mean-subtracted both and ), the intercept would naturally be near zero anyway — but you still do not penalize it.

Pitfall: When implementing Ridge, make sure your code skips in the penalty. A common bug is to regularize all parameters including the intercept.

Recap. Ridge = L2 penalty = sum of squared coefficients. It shrinks all coefficients toward zero proportionally but never eliminates any. Use it when all features matter at least a little. Next: Lasso — the sibling that CAN eliminate features (Section 6.6).

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)

Hook. What if your regularizer could not only shrink coefficients but eliminate useless features entirely — setting their coefficients to exactly zero? That is Lasso. It does automatic feature selection while it trains.

6.6.1 Definition

Intuition + Analogy. Ridge (Section 6.5) is like a committee where everyone gets a softer voice. Lasso is like a committee where some members get voted off entirely. The penalty is proportional to the absolute value of each coefficient, not its square. This means the penalty grows linearly with coefficient size — a coefficient of 10 pays 5× the penalty of a coefficient of 2 (compared to 25× for Ridge).

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.

Lasso stands for Least Absolute Shrinkage and Selection Operator. It adds a penalty equal to the sum of absolute values of coefficients (the L1 norm):

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

Lasso penalty scaling vs. Ridge:
CoefficientsLasso penaltyRidge 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

Taking the derivative of the Lasso cost function. The derivative of with respect to is — the sign function:

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

In Lasso, the penalty's contribution to the update is a constant — it does not depend on how large or small is. The update always adds or subtracts (with the sign determined by ).

Contrast with Ridge:

Ridge (L2)Lasso (L1)
Penalty contribution to update (depends on ) (constant magnitude)
Large coefficientLarge shrinkageSame constant push
Small coefficientSmall shrinkageSame constant push
Zero coefficientZero pushCan 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

Lasso regression can shrink coefficients all the way to exactly zero. When , that feature is eliminated from the model — it contributes nothing to predictions. This makes Lasso a form of automatic feature selection.

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 to use Lasso. Use Lasso when you have many features but suspect many are useless. If domain knowledge tells you only a subset of features matter, Lasso automatically identifies and keeps the important ones while zeroing out the rest. This gives you both a predictive model AND feature selection in one step.

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

Q: How is the sign decided for ? How does it become plus or minus?

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

Overshooting risk. Because Lasso applies a constant push regardless of coefficient size, it can overshoot. Imagine (positive) and . The Lasso update subtracts 0.1, making — the coefficient jumped past zero to the opposite side. Next iteration, flips, the penalty adds 0.1, and jumps back to . The coefficient oscillates.

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.

Recap. Lasso = L1 penalty = sum of absolute coefficients. It applies a constant push toward zero regardless of coefficient size, which can drive coefficients exactly to zero — automatic feature selection. Use when you suspect many features are irrelevant. Next: combining both penalties — Elastic Net (Section 6.7).

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

Hook. Ridge keeps all features. Lasso kills some. What if you want the best of both — shrink most coefficients while still being able to eliminate the truly useless ones? Enter Elastic Net.
Intuition + Analogy. Elastic Net is like a tax code with two brackets: a flat per-feature tax (Lasso's L1) plus a proportional tax on squared coefficient size (Ridge's L2). The L1 part can zero out useless features; the L2 part stabilizes the remaining ones — especially when features are correlated (where Lasso alone tends to pick one correlated feature arbitrarily and ignore the rest).
Elastic Net combines both L1 and L2 penalties in a single cost function. The penalty term:

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.

Comparison — Ridge vs. Lasso vs. Elastic Net:
PropertyRidge (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?NoYes (automatic)Yes (automatic)
Best whenAll features matterMany features are uselessSome 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.

Pitfall. Elastic Net has TWO hyperparameters ( and ) instead of one. This doubles the grid search space. Start with a coarse search, then refine.
Recap. Elastic Net = Ridge + Lasso. It gives you Lasso's feature selection with Ridge's stability for correlated features. Next: how to choose the penalty strength — the regularization parameter (Section 6.8).

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 ()

Hook. is the single most important knob in regularized regression. Turn it to zero and regularization disappears. Turn it too high and your model predicts the same constant for everything. How do you find the Goldilocks value?

6.8.1 Role

(lambda) controls the strength of the penalty — how much the model is taxed for large coefficients. It appears in Ridge, Lasso, and Elastic Net cost functions. Think of as the tax rate: means zero tax (OLS), means infinite tax (all forced to zero).

6.8.2 Effect of Different Lambda Values

ValueEffectModel Behavior
No penaltyPure 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 penaltyGood tradeoff: fits the data well while keeping coefficients modest.
large (e.g., )Strong penaltyMost coefficients near zero. Model approaches a horizontal line (just ).
Infinite penaltyAll for . Model = = mean of . Complete underfitting.
Visual intuition. Plot on the x-axis (log scale) and model error on the y-axis. You will see a U-shaped curve: high error at (overfitting → high test error), a sweet spot at moderate (lowest test error), then rising error as increases (underfitting). The training error monotonically increases with — it is the test error that shows the U-shape.

6.8.3 How to Choose Lambda

There is no single "right" — it depends on your data. The standard approach:

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.

Pitfalls.

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.

Recap. controls penalty strength. = OLS (overfitting risk), = constant prediction (underfitting). Choose by cross-validation on a log scale. Next: putting the math into practice — worked gradient descent examples (Sections 6.9–6.11).

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)

Hook. Time to compute. This section walks through one complete iteration of gradient descent for linear regression with real numbers. If you can follow every step here, you understand how linear regression is actually trained.

6.9.1 Problem Setup

Dataset: Predicting the relative risk of coronary heart disease (CHD) — target variable — from two features: - : BMI (Body Mass Index) - : Diastolic blood pressure

Given parameters:
- (learning rate)
- (intercept)
- (coefficient for BMI)
- (coefficient for diastolic pressure)
- (three patients)

Hypothesis function:


6.9.2 Iteration 1 — Step-by-Step

Step 1: Compute predicted values for each patient.

The three patients have the following data (reconstructed from the lecture context):

Patient (BMI) (Diastolic BP) (CHD risk)
135801.81
232901.95
3301002.10

Patient 1:

Patient 2:

Patient 3:

Step 2: Compute error for each patient.

Patient error
11.551.81
21.341.95
31.102.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)

Critical rule: To do iteration 2, you MUST recompute predictions using the NEW values from iteration 1. Then recompute errors, recompute gradients, and update again. Many students forget this — they keep using the old predictions from iteration 1, which produces wrong gradients for iteration 2.

Each iteration is a fresh calculation: predict → error → gradient → update → repeat.

Recap. One gradient descent iteration = predict with current → compute errors → compute gradients via → update with step size . The unscaled features produced wild updates — demonstrating why scaling matters. Next: the same dataset with Ridge regularization applied (Section 6.10).

6.10 Worked Example — Ridge Regression (2 Iterations)

Hook. How does the Ridge penalty actually change the numbers? This section applies the Ridge update rule to the same CHD dataset from Section 6.9 — and reveals why feature scaling is not optional.

6.10.1 Setup

Same dataset as Section 6.9: three patients, predicting CHD risk from BMI () and diastolic blood pressure (). Initial parameters: , , .

Additional given:
- (regularization constant)
- (unchanged)
- Apply Ridge update rule for 2 iterations

6.10.2 Computing the Shrinkage Factor

The Ridge shrinkage factor (derived in Section 6.5.2):

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 1 — Predictions (same as Section 6.9, 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

Step 1 — Recompute predictions with Ridge iteration-1 parameters:

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

Why the model "failed." The coefficients did not converge to useful values because:

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).

Recap. Ridge applies a multiplicative shrinkage to each coefficient every iteration, alongside the standard data-error gradient step. Without feature scaling, the data-error gradient dominates the shrinkage, producing unstable coefficients. The computation process is correct; the input data needs preprocessing. Next: the same dataset with Lasso (Section 6.11).

6.11 Worked Example — Lasso Regression (2 Iterations)

Hook. Same dataset, same and — but now with Lasso's constant-push penalty instead of Ridge's proportional shrinkage. Watch what happens when the penalty is a fixed amount rather than a percentage.

6.11.1 Setup

Same CHD dataset as Sections 6.9–6.10. Initial parameters: , , . , .

6.11.2 Computing the Constant Penalty Term

The Lasso penalty contribution per iteration (derived in Section 6.6.3):

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

Initial coefficients: (negative), (negative).

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

Step 1 — Recompute predictions using Lasso iteration-1 parameters: , , .

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

MethodUpdate mechanismIteration 1 Behavior
Simple LRData gradient onlyFast, no regularization
Ridge + data gradientSlightly 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

Q: If theta is negative like , how do we interpret it? How does it affect the final output?

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.

Recap. Lasso's constant penalty is added when and subtracted when , always pushing toward zero. With unscaled data, this constant push is dwarfed by the data gradients. The penalty's sign-flipping behavior can cause oscillation. Next: the cure — feature scaling (Section 6.12).

6.12 Data Preprocessing and Feature Scaling

Hook. The worked examples in Sections 6.9–6.11 produced terrible models — not because the math was wrong, but because the data was raw. This section explains the single most important step before any modeling: scaling your features.

6.12.1 Why Scaling Matters

Intuition + Analogy. Imagine trying to measure the distance between two cities. One map uses kilometers, another uses millimeters. On the same optimization problem, gradient descent is trying to find the shortest path — but the "millimeter" features create a landscape that is stretched 1,000,000× in one direction. The hiker (gradient descent) takes steps that are too small for the millimeter direction and too large for the kilometer direction. Scaling converts everything to the same units — like putting both maps on the same scale.

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

The standard method: standardization (Z-score normalization). For each feature :

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.

Scaling the CHD dataset (example):

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

The principle: good data → good output. Bad data → bad output, no matter how sophisticated the model.

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

Feature engineering is the process of transforming raw data into features that a model can use effectively. It includes:

- 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.

Recap. Unscaled features distort gradient descent by creating an elongated cost surface. StandardScaler (Z-score) fixes this. Always scale before regularizing — otherwise the penalty is applied unevenly across features. Next: deploying models with scikit-learn pipelines (Section 6.13).

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

Hook. You have scaled your features, imputed missing values, trained a Ridge model, and tuned . Now how do you package all of this so it works reliably in production — without redoing every step manually?

6.13.1 scikit-learn Pipelines

Purpose. An ML Pipeline chains preprocessing and modeling steps into a single object. You call 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.

Pipeline trace (conceptual):

``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.

Pitfall. Never fit the scaler on test data. The pipeline prevents this automatically — 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

Joblib is a Python library for saving (serializing) trained models to disk. Models are saved in .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

Streamlit is a Python framework for building data web apps with minimal code — no HTML/CSS/JavaScript required. You can:

- 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

The core ML workflow has three stages:

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

Q: Can we use ML pipelines for the assignment?

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.

Recap. Pipelines chain preprocessing + modeling into a single 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.15 Student Q&A — Model Performance Issues

Several students asked about diagnosing and fixing poor model performance — a very common concern. Here are the professor's answers, consolidated.
Q: My training RMSE is around 0.2–0.3, but test RMSE jumps to 1.2–1.3. How can I improve this?

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.

Q: Should we exclude the original columns from the CSV before giving it to the model, or keep both original and new columns?

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.

Recap. Training error ≪ test error = overfitting → tune , check scaling, clean data. Feed only preprocessed columns to the model; keep raw data separately. Next: visualizing what gradient descent actually does — contour plots (Section 6.16).

6.16 Gradient Descent — Contour Plot Visualization

Hook. You have been updating numerically. But what does gradient descent actually look like — visually — as it searches for the minimum?

6.16.1 The Convex Bowl

Intuition + Analogy. The cost function for linear regression is a convex bowl. Drop a marble anywhere on the inner surface and it rolls to the bottom — that one bottom point is the global minimum. Gradient descent is that marble, but taking discrete steps instead of rolling continuously.

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

Visual intuition. Picture two side-by-side plots:

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

With regularization, the hiker (gradient descent) is now looking for two slopes simultaneously:

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 .

Recap. The cost function is a convex bowl. Contour plots show concentric ellipses around the minimum. Gradient descent walks from the initial guess toward the center. Regularization adds a second bowl (centered at the origin), and gradient descent finds the compromise. Next: regularization applies the same way to logistic regression (Section 6.17).

6.17 Connection to Logistic Regression

Hook. You have learned regularization for linear regression. But what about classification — where the output is "spam" or "not spam" rather than a number? The regularization concept transfers directly.

6.17.1 Same Penalty Concept, Different Cost Function

Logistic regression uses a different cost function — log loss (also called cross-entropy) — instead of mean squared error. But the regularization concept is exactly the same:

- 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

Understanding regularization for linear regression is essential because the same concept applies directly to logistic regression, support vector machines, neural networks (where it is called "weight decay"), and virtually every other ML model. If the concept of Ridge and Lasso is clear now, you already understand the regularization component of all these models. The only new thing each model adds is its specific loss function.

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

Exam note: Assignment guidance — consolidated from multiple points in the lecture.

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

- Grading is relative — there are no fixed passing marks. Your grade depends on how you perform compared to the rest of the class. - The highest score in the class gets an A grade. Other grades are assigned relative to that top score. - Scoring approximately 40 marks (out of ~100) across assignments, quizzes, mid-semester, and end-semester exams typically places a student within the passing grade range. - E grade means the course must be repeated — it is the university's term for what is commonly called "fail."

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.

Recap. One submission, implement manually, experiment beyond requirements, relative grading. Feature engineering and hyperparameter tuning are the levers that move your score.

6.19 Key Industry Applications and Tools

Tool / ConceptPurposeUsed In
scikit-learnPython ML library — provides LinearRegression, Ridge, Lasso, ElasticNet, Pipeline, GridSearchCV, StandardScalerIndustry standard for classical ML; used by Spotify, Airbnb, JPMorgan
JoblibModel serialization — save/load trained models in .pkl or .joblib formatProduction deployment; part of the scikit-learn ecosystem
StreamlitPython framework for building ML web apps with minimal code (no HTML/CSS needed)Rapid prototyping, internal tools, demos; used by Uber, Delta, Snowflake
Streamlit CloudOne-click deployment of Streamlit appsSharing models with non-technical stakeholders
GridSearchCVAutomated hyperparameter tuning with cross-validationModel selection in every ML project
Cross-validationEvaluating model performance by training on multiple data splitsReliable performance estimation; standard in academic papers and industry
StandardScalerFeature scaling — transforms features to mean 0, standard deviation 1Preprocessing step in virtually every regression pipeline
ML PipelinesChaining preprocessing and modeling steps for productionPrevents train-test leakage; enables one-click retraining
Decision TreesAlternative non-linear model typeBaseline comparison; interpretable models for regulated industries
Domain connection. Regularized linear regression (Ridge/Lasso) is the starting point for predictive modeling in nearly every quantitative field:

- 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

SituationMethod
All features matter, data is cleanRidge (L2)
Many features, some are noiseLasso (L1)
Unsure, or features are correlatedElastic Net
unknownGridSearchCV with cross-validation
Raw data, different scalesStandardScaler FIRST

ML Lecture 6 notes · Regularization — Worked Numerical Examples

Machine Learning· postgraduate· 2026-06-29

Sections Breakdown

1Review of Linear Regression Fundamentals

Hypothesis function, cost function (MSE), closed-form solution (Normal Equation), and gradient descent update rule.

2Overfitting

Definition, visual representation, recognizing overfitting from large coefficients, consequences.

3Bias and Variance

Bias-variance tradeoff definitions, the four conditions (high/low bias/variance).

4Regularization — Core Concept

Intuition, standard vs regularized regression, penalty term as tax on complexity.

5Ridge Regression (L2)

Definition, cost function, gradient descent update rule with shrinkage factor.

6Lasso Regression (L1)

Definition, cost function, constant push update rule, automatic feature selection.

7Elastic Net

Combined L1 + L2 penalty, mixing parameter R, comparison of all three regularizers.

8The Regularization Parameter Lambda

Role of lambda, effect of different values, how to choose via cross-validation.

9Worked Example — Simple Gradient Descent

One full iteration of gradient descent on CHD dataset.

10Worked Example — Ridge Regression

Two iterations of Ridge gradient descent showing shrinkage factor effect.

11Worked Example — Lasso Regression

Two iterations of Lasso gradient descent showing constant push behavior.

12Data Preprocessing and Feature Scaling

Why scaling matters, StandardScaler (Z-score), feature engineering overview.

13ML Pipelines and Model Deployment

scikit-learn Pipelines, Joblib model serialization, Streamlit apps.

14Hyperparameter Tuning and Grid Search

GridSearchCV, cross-validation procedure, common pitfalls.

15Student Q&A — Model Performance Issues

Diagnosing overfitting, feature engineering advice, data preprocessing.

16Gradient Descent Visualization

Convex bowl analogy, contour plots, regularization effect on the minimum.

17Connection to Logistic Regression

Same penalty concept applies, weight decay in neural networks.

18Assignment Guidance Summary

Submission rules, relative grading, key advice for the assignment.

19Key Industry Applications and Tools

scikit-learn, Joblib, Streamlit, real-world applications.

20Key Formulas Reference

Consolidated formulas for linear regression, Ridge, Lasso, Elastic Net.

Postgraduate students in Machine Learning

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?

Loading comments…
🤖

BitsNotes AI Assistant

Subject Notes Assistant

Configure AI Chat

Choose how to access the chatbot
Have your own API key?

Switch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.

🔑 Enter API key above to fetch live models from provider, or enter model name manually.
OpenAI-Compatible API Support

Choose any provider preset (Gemini, DeepSeek, Kimi, GLM, MiniMax, Qwen, OpenAI, Groq, Ollama, etc.) or enter a custom endpoint URL.

Security & Privacy First

Your API key is sent directly from your browser to your specified provider. BitsNotes servers never store or see your key.