Welcome to the next lesson in our final module. In our previous lesson, we explored a practical solution to a common optimization headache: ill-conditioning. You learned how feature scaling can reshape a treacherous, canyon-like loss surface into a symmetrical bowl, dramatically accelerating the convergence of gradient descent. This was a form of preconditioning—manipulating the data to make the problem easier for the algorithm.
Today, we shift our focus from fixing the data to improving the model itself. We'll investigate what happens when a model fits the training data too well, a phenomenon known as overfitting. You will learn about Ridge Regression, also known as L2 regularization, a fundamental technique that prevents overfitting by intelligently modifying the optimization objective. By the end of this lesson, you will be able to explain how adding a specific penalty term to the loss function biases the model's parameters towards smaller values, resulting in solutions that are often more robust and generalize better to new data.
The Peril of Overfitting: When Perfect is the Enemy of Good
In machine learning, our goal is to build models that learn general patterns from data. However, a flexible model, if not properly constrained, can learn not just the signal but also the noise in the training set. This is called overfitting. An overfit model performs exceptionally well on the data it was trained on but fails spectacularly when faced with new, unseen data.
A common symptom of an overfit linear model is that it has extremely large coefficients (weights). To fit every little nook and cranny of the training data, the model might resort to a "spiky" function with huge positive and negative weights that cancel each other out to pass through the specific data points.
The following video from StatQuest provides an excellent and intuitive introduction to this problem.
Regularization Part 1: Ridge (L2) Regression
Josh Starmer's StatQuest videos are famous for their clarity. This one introduces the core problem that Ridge Regression solves.
Watch the segment from the beginning of the example. Pay close attention to how fitting a line to just two data points (the "training data") using the standard least squares method results in a perfect fit for those points but a terrible fit for the rest of the data (the "testing data"). This is a classic demonstration of high variance and overfitting.
The video introduces the central idea of Ridge Regression: by accepting a slightly worse fit on the training data (introducing a small amount of bias), we can achieve a significant drop in variance, leading to a model that performs much better in the long run.
The Solution: A New Objective Function
How do we encourage a model to avoid large weights? We change its objective. Instead of only asking the model to minimize the error between its predictions and the true values, we add a second term to the loss function: a penalty for having large weights.
This is the essence of Ridge Regression. The standard Mean Squared Error (MSE) loss for linear regression is:
Ridge Regression modifies this by adding a penalty proportional to the squared L2-norm of the weight vector, :
Let's break this down:
- MSE Term: This is the familiar "goodness-of-fit" term. It pushes the weights to values that make the model's predictions as close as possible to the true outcomes .
- Penalty Term (): This is the L2 regularization term. It penalizes the sum of the squared weights. To minimize this part of the loss, the optimizer must make the weights as small as possible.
- (Lambda): This is the regularization parameter, a hyperparameter that you choose. It controls the strength of the penalty.
- If , the penalty term vanishes, and we are back to standard Ordinary Least Squares (OLS) regression.
- As increases, the model is penalized more heavily for large weights, forcing them to shrink.
The optimizer's job is now to find a set of weights that strikes a balance between these two competing goals: fitting the data well and keeping the weights small. This trade-off is the heart of regularization.
Let's return to the StatQuest video to see how this plays out.
Regularization Part 1: Ridge (L2) Regression
Now we'll see the Ridge loss function in action and understand the role of lambda.
Watch from the introduction of the Ridge equation. Notice how the new penalty term changes which line is considered "best". The line with a slightly higher residual error but a much smaller slope now wins. Continue from this segment to solidify the connection between large slopes (large weights) and high sensitivity. Shrinking the slope makes the model's predictions more stable. Next, see how \lambda controls this effect from this section. As \lambda increases, the slope is forced closer and closer to zero. Finally, see how this generalizes to multiple features from this explanation and in the final summary. The penalty includes all parameters except the y-intercept.
Biasing the Solution: How It Works Mechanically
The new penalty term actively biases the solution away from the one that OLS would have found. Let's see this from two perspectives: gradient descent and the geometric interpretation.
1. The Gradient Descent View: Weight Decay
Recall the update rule for gradient descent: we update the weights by taking a step in the direction of the negative gradient of the loss function.
With Ridge regression, the gradient of the loss function now has an extra term from the penalty:
So, the update rule becomes:
We can rearrange this slightly:
Look closely at the (1 - 2ηλ) term. At every step, before we even compute the gradient from the error, we first shrink the current weight vector by a small factor. This is why L2 regularization is often called weight decay. It constantly pulls the weights towards the origin during training, fighting against the error gradient's attempts to make them too large.
The following resource provides a clear explanation of the loss functions and the resulting gradient descent updates.
Intuitions on L1 and L2 Regularisation - Towards Data ...
This article from Towards Data Science breaks down the math of regularization.
First, familiarize yourself with the definitions in the sections on L1 and L2 norms and the L2 loss function. Next, review the gradient descent update equations. Notice the 2λw term in the gradient for L2. Finally, read the section comparing L1 and L2 updates. The key insight for us is how the -2λw term in the L2 update means the change in w depends directly on the current magnitude of w, creating the shrinkage effect.
2. The Geometric View: A Tale of Two Bowls
Your preference for geometric intuition will serve you well here. We can visualize the loss function in the parameter space.
- The MSE loss surface is a parabolic bowl (or a paraboloid in higher dimensions). The bottom of this bowl represents the optimal OLS solution, .
- The L2 penalty term, , is also a parabolic bowl, but it's perfectly symmetrical and centered at the origin ().
- The Ridge loss surface is the sum of these two bowls.
The minimum of this new, combined surface is no longer at . Instead, it's at a point that is pulled from the OLS solution towards the origin. How far it's pulled depends on the value of .

Another powerful geometric view frames this as a constrained optimization problem. Minimizing the Ridge loss is equivalent to solving:
"Minimize the MSE, subject to the constraint that the size of your weight vector, , cannot exceed a certain budget."
This budget is represented by a circle (in 2D) or a hypersphere (in higher dimensions) centered at the origin. The OLS solution lies at the center of the elliptical contour lines of the MSE loss. The Ridge solution is found at the point where the expanding ellipses of the MSE loss first "touch" the boundary of the circular L2 constraint.

This excellent guide provides further visualization and a concrete numerical example of this shrinkage effect.
Ridge Regression (L2 Regularization) - Michael Brenndoerfer
This comprehensive guide will solidify your understanding with clear explanations and visuals.
Start by reading the introductory section "L2 Regularization (Ridge)" to get a high-level summary. Look at the formula section, noting both the summation and matrix notation. Examine the plot in the section on the Regularization Path. This shows how all coefficients shrink smoothly towards zero as \lambda increases. The next plot shows the effect on a simple 2D regression line, which becomes flatter (smaller slope) as \lambda grows. Walk through the numerical Example. Pay close attention to the final comparison table showing the OLS coefficients vs. the smaller Ridge coefficients. Finally, read the brief "Examining the Coefficients" and the Summary to wrap up.
Key Takeaways
You have now explored the motivation, mechanics, and geometry behind Ridge regression. This technique is a cornerstone of building robust machine learning models.
- Objective: Ridge regression (L2 regularization) combats overfitting by adding a penalty term, , to the loss function.
- Mechanism: This penalty discourages the model from using large weights, forcing it to find simpler solutions.
- Effect: The resulting solution is biased towards smaller parameter values. It deliberately accepts a slightly higher error on the training data in exchange for lower variance and better generalization to unseen data.
- Control: The hyperparameter controls the strength of this regularization, managing the trade-off between fitting the data and shrinking the weights.
- Geometry: This process can be visualized as finding the minimum of a combined loss surface (MSE bowl + L2 penalty bowl) or as finding the lowest-error solution that fits within a circular "budget" for the weights.
In our next and final lesson, we will complete this picture. We'll analyze how L2 regularization also has the beneficial side effect of improving the matrix's condition number, connecting back to our previous discussions. We will also contrast Ridge with its famous cousin, Lasso (L1) regression, which uses a different penalty to achieve a very different, and equally useful, kind of bias.