Exercises — L2 (Ridge) regularization
This is the practice set for Ridge regression. Every problem is stated cleanly, then fully solved inside a collapsible Solution callout so you can test yourself first. Problems climb from L1 Recognition (do you know the pieces?) up to L5 Mastery (can you invent and combine?). After each level there is one [!mistake] callout naming the trap most people fall into there.
Everything here rests on two facts from the parent note, restated so nothing is assumed:
Level 1 — Recognition
L1.1
Write the Ridge cost for a single feature (no intercept), with data pairs for the training examples and strength . Then identify which term is the "data fit" and which is the "penalty".
Recall Solution
With one weight and one feature, the prediction for example is . The squared error over all points (recall = number of training examples) plus the penalty is The first sum measures how far predictions land from truth; the second charges a fee for every unit of used.
L1.2
For , what does Ridge reduce to? For , what does approach?
Recall Solution
- : the penalty term vanishes, — this is exactly Ordinary Least Squares.
- : the fee on weight-size dominates everything, so the cheapest choice is . Every weight is squeezed toward zero (maximum underfit).
L1.3
True or false, with a one-line reason each: (a) Ridge can set a weight exactly to . (b) Adding can make a non-invertible invertible.
Recall Solution
(a) False. Ridge's penalty is a smooth circle/sphere; it shrinks weights continuously but generically never hits exactly . Exact zeros are Lasso's specialty (its diamond has corners on the axes). (b) True. is positive semi-definite (eigenvalues ). Adding with lifts every eigenvalue by , making them all strictly positive → the matrix is invertible.
Level 2 — Application
L2.1
Scalar Ridge. You are given and . Compute for , , and .
Recall Solution
From L1.1, setting gives , so
- : (this is OLS).
- : .
- : . Notice the pattern: Ridge only inflates the denominator. Bigger → bigger denominator → smaller , monotonically toward .
L2.2
Two-feature closed form. Let Compute .
Recall Solution
Step 1 — build . Multiply columns of pairwise: Step 2 — add (here , so adds to each diagonal entry): Step 3 — build . Dot each column of with : Step 4 — invert and multiply. For a matrix the inverse is . Here :
L2.3
Feature-scaling fairness. Feature is a length in meters; you rescale it to millimeters (multiply by ). To keep the same predictions, the weight must be divided by . If the penalty is , by what factor does the penalty on this feature change?
Recall Solution
New weight . Penalty term . So the penalty on this one feature is cut by a factor of even though nothing about the underlying relationship changed. That is exactly why we standardize first — otherwise the penalty is a lottery decided by measurement units. See Feature Scaling / Standardization.
Level 3 — Analysis
L3.1
Prove monotone shrinkage. Show that in the scalar case (with , ) has strictly decreasing in for when , handle the edge case , and find .
Recall Solution
Edge case first. If , then for every . So is constant, not strictly decreasing — there is simply nothing to shrink. Keep this exception in mind; the strict-decrease claim needs . Main case . We want the sign of , so write the magnitude directly. Since , This is a genuine function of (no absolute-value kink, because the denominator never changes sign). Differentiate it: With we have and , so for all . A function with strictly negative derivative is strictly decreasing — exactly what we set out to prove. (This is cleaner than tracking and signs of separately: differentiating itself leaves no gap.) Limit. As the denominator , so . More penalty → smaller, calmer weight, moving toward zero and never overshooting past it.
L3.2
Correlated twins. Suppose two features are identical: , and any weights with fit the training data equally well (they all produce the same predictions). Among all such pairs, which one does Ridge choose, and what is its penalty?
Recall Solution
Ridge breaks the tie by the smallest penalty among equally-good fits. We minimize subject to . Substitute : Set , hence . Penalty . Compare a cancelling solution like (also on some fitting line for near-twins): penalty . Ridge overwhelmingly prefers the even split . Read the figure. The solid black line is the set of all fitting pairs (). The dashed circle is the smallest weight-budget circle that still touches this line; it kisses the line at exactly the point nearest the origin. The red dot marks that tangency point — the even split. Every other fitting pair (like the far black dot toward ) lies on a bigger circle → larger penalty. This is why Ridge spreads weight across correlated features instead of letting them explode in opposite directions.

L3.3
SVD shrinkage direction. Using the parent's result, the effective factor along singular direction is . For , compute for a strong direction and a weak direction . Which is shrunk more?
Recall Solution
- Strong: — kept almost intact.
- Weak: — crushed to one-fifth. The weak (small-) direction is shrunk far more. Small means that direction was measured with little energy in the data — it is where noise dominates. Ridge distrusts it and keeps the confidently-measured strong direction. Read the figure. The black curve plots the kept fraction against the singular value (with ). It rises from (at , fully crushed) toward (the dotted line, kept in full) as grows. The two red dots mark our cases: the weak sits low at , the strong sits high at . The gap between them is the whole story — Ridge trusts strong directions and distrusts weak ones. See Singular Value Decomposition.

Level 4 — Synthesis
L4.1
Derive the scalar solution from the constrained view. The parent note states that minimizing is equivalent to minimizing the fit subject to a budget , where is the largest squared weight-length the model is allowed to spend (a smaller means a tighter leash). For the 1D case with fit term (where ) and budget , show that if the OLS optimum violates the budget, the constrained optimum sits exactly on the boundary (assume ), and show how a specific produces that same .
Recall Solution
First, what is ? It is the weight budget: the constrained problem says "minimize the fit, but you may only spend up to of squared weight-length." In 1D, means — the weight is boxed into the interval . The unconstrained fit minimizer is (set ). The fit term is a convex parabola with , so it decreases as moves from up to , then increases. If , then over the allowed interval the parabola is still on its decreasing side (we never reach the vertex). The smallest fit inside the budget is therefore at the largest allowed , i.e. . The constraint is active (binding). How matches . The penalized problem gives (from L2.1). Set this equal to the boundary value and solve for the matching : Since means , this is positive — exactly the regime where the budget binds. So each budget corresponds to one penalty , and both problems return the same shrunken weight . That is the concrete "two faces of one coin" correspondence: tighter budget (smaller ) ⟺ heavier penalty (larger ).
L4.2
Ridge meets logistic. Plain Logistic Regression can drive weights to when the classes are perfectly separable (the loss keeps improving as weights grow). Explain in one paragraph why adding an L2 penalty fixes this, and what it does to the decision boundary's "confidence".
Recall Solution
With perfect separation, the logistic (log-loss) objective has no finite minimizer — pushing makes the sigmoid outputs saturate to exactly and the loss keeps dropping toward zero without ever reaching it. Adding inserts a term that grows without bound as . Now the total objective (log-loss + penalty) does have a finite minimizer: the fit still wants to grow the weights, but the penalty fee eventually outweighs the shrinking loss gain, so growth stops at a finite . Effect on the boundary: the location of the boundary stays sensible, but its slope/confidence is tempered — because the weight magnitudes are held finite, the sigmoid no longer saturates instantly, so predicted probabilities near the boundary stay soft (not slammed to or ). Softer, calibrated probabilities generalize better on unseen data. This is the classification cousin of Ridge curing the ill-posed OLS problem: in both cases the term supplies the missing "floor" that makes a runaway optimization settle at a finite, stable answer.
L4.3
Combine the pieces. You have features but only training examples. (a) Why is plain OLS impossible here? (b) Why does Ridge still return a unique answer? (c) Name one other estimator from your vault that would also give a sparse solution and say when you'd prefer it.
Recall Solution
(a) With , the matrix (size ) has rank at most , so it is singular — not invertible — and OLS does not exist (infinitely many perfect fits). (b) Ridge solves . Adding () lifts all eigenvalues above , so the matrix is strictly positive definite → invertible → unique solution, even when . (c) Lasso (L1) would give a sparse weight vector (many exact zeros) — prefer it when you believe only a handful of the 500 features truly matter and you want automatic feature selection. If you want both grouping of correlated features (Ridge-like) and sparsity (Lasso-like), use Elastic Net.
Level 5 — Mastery
L5.1
Effective degrees of freedom. The "effective number of parameters" Ridge uses is (sum of the SVD shrinkage factors). For a design with singular values , compute at and , and interpret.
Recall Solution
.
- : — full model, both directions counted (this is the OLS parameter count).
- : . Interpretation: at Ridge behaves like a model with only effective parameters — dramatically simpler than the nominal . The strong direction contributes , the weak one only . This continuous dial from down toward is precisely how Ridge slides along the Bias-Variance Tradeoff.
L5.2
Design a cross-validation experiment. You want to pick for a Ridge model. Lay out a correct 5-fold cross-validation procedure, and explain the one preprocessing step that must happen inside each fold, not before.
Recall Solution
Procedure.
- Choose a grid, e.g. (log-spaced).
- Split the training data into 5 folds.
- For each : for each fold , train on the other 4 folds and evaluate MSE on fold ; average the 5 MSEs → .
- Pick — the valley of the validation curve.
- Refit on all training data with ; report on the untouched test set. The inside-the-fold step: standardization (subtracting the mean, dividing by std) must be computed on the training portion of each fold only, then applied to the held-out portion. If you standardize on the full dataset first, statistics from the validation rows leak into training and your CV estimate is optimistically biased. Never pick by training error — it decreases monotonically toward and always lies to you.
L5.3
Full mini-pipeline by hand. Given compute (a) the OLS weights, (b) the Ridge weights at , and (c) the ratio for each component. Show that the ratio equals the SVD shrinkage factor and identify .
Recall Solution
(a) OLS. Here is diagonal so and . (b) Ridge, . , so (c) Ratios. and . Both are . SVD check. , so its singular values are both , giving . The shrinkage factor is — matching the observed ratio exactly. The SVD story ("scale each direction by ") is not an abstraction; it is what the closed form does, component by component.
Recall One-line summaries to self-quiz
Scalar Ridge weight ::: — Ridge only inflates the denominator Why breaks OLS but not Ridge ::: is singular; makes it invertible Ridge's choice among correlated twins ::: even split (min ), e.g. not SVD shrinkage factor ::: ; weak directions shrunk most Effective degrees of freedom ::: , slides from toward Standardization in CV ::: fit scaler inside each fold, never on the full set