Hello! Let's get started on our next lesson.
In our previous session, we explored how polynomial regression can model complex, non-linear relationships. We also saw its major weakness: a high-degree polynomial can create an overly complex model that fits the noise in the training data perfectly but performs poorly on new data. This phenomenon, which you know as overfitting, is often characterized by very large model coefficients that cause the function to fluctuate wildly.
This lesson directly addresses that problem. We will explore regularization, a powerful set of techniques used to constrain the complexity of machine learning models, preventing them from overfitting. Specifically, we'll focus on two of the most popular regularization methods for regression: Ridge Regression (L2) and Lasso Regression (L1). You will learn how they work, their key differences, and how to use them in Python to build more robust and reliable models.
By the end of this lesson, you will be able to apply these regularization techniques to control model complexity and prevent overfitting, a crucial skill for any machine learning practitioner.
1. The Core Idea: Penalizing Complexity
Let's start with the model from our last lesson. A simple linear regression model has a cost function based on the Residual Sum of Squares (RSS):
When we used a high-degree polynomial, the model could minimize this RSS to almost zero by creating a very "wiggly" curve with large positive and negative coefficients.
Regularization introduces a simple but brilliant modification: it adds a penalty term to the cost function. This new cost function forces the model to perform a balancing act:
- Fit the data well (keep the RSS low).
- Keep the model simple (keep the coefficients small, thus minimizing the penalty).
The general form of a regularized cost function is:
This approach is a direct application of the bias-variance tradeoff. We intentionally introduce a small amount of bias (by not letting the model fit the training data perfectly) to achieve a significant reduction in variance (leading to better generalization on unseen data).
The following video provides an excellent intuitive introduction to this concept, showing how we can get a better long-term model by accepting a slightly worse fit on the training data.
Regularization Part 1: Ridge (L2) Regression
Let's watch the first part of 'Regularization Part 1: Ridge (L2) Regression' from the StatQuest with Josh Starmer channel. It clearly illustrates the problem of overfitting with a simple example and introduces the core idea of regularization.
Watch from 02:21 to 04:15. Focus on how the line fit to just two 'training' data points is 'overfit' and has high variance when tested against the other 'testing' data points. Notice the key idea: introducing bias to reduce variance.
Now, let's see how this penalty is specifically implemented in Ridge and Lasso regression.
2. Ridge Regression (L2 Regularization)
Ridge Regression adds a penalty proportional to the sum of the squares of the coefficients. This is also known as an L2 penalty.
The Ridge cost function is:
Let's break this down:
- is the L2 penalty: the sum of the squared values of all coefficients ( to ). Note that the intercept term is usually not penalized.
- (lambda) is a hyperparameter that controls the strength of the regularization.
- If , the penalty term disappears, and Ridge regression becomes identical to ordinary least squares (OLS).
- As increases, the penalty becomes more influential, and the model's coefficients are "shrunk" more aggressively towards zero.
- If , all coefficients will approach zero, resulting in a flat line (underfitting).
The optimal value of is usually found through cross-validation. In scikit-learn, this hyperparameter is named alpha.
To see how this works in practice, let's continue with the StatQuest video. It gives a fantastic numerical example of how the penalty term influences the final model.
Regularization Part 1: Ridge (L2) Regression
This next segment from the StatQuest video on Ridge Regression explains the L2 penalty in detail and demonstrates the role of the lambda parameter.
Watch from 04:15 to 07:27 and then from 08:40 to 10:26. Pay close attention to: How the total value to be minimized is calculated (RSS + penalty). How the ridge regression line, despite having a higher RSS than the OLS line, wins because of the smaller penalty. The effect of increasing the lambda value on the model's slope.
A key property of Ridge regression is that it shrinks coefficients towards zero, but it will never set them exactly to zero (unless is infinite). This means Ridge regression always keeps all features in the model; it only reduces their influence.
3. Lasso Regression (L1 Regularization)
Lasso Regression (Least Absolute Shrinkage and Selection Operator) works similarly, but it uses a different penalty: the sum of the absolute values of the coefficients. This is known as an L1 penalty.
The Lasso cost function is:
The only difference is the penalty term: instead of . This might seem like a small change, but it has a profound effect.
The crucial difference is that Lasso can shrink some coefficients all the way to zero. This means Lasso can perform automatic feature selection, effectively removing useless features from the model by making their coefficients zero. This results in "sparse" models (models with few non-zero coefficients), which are often simpler and more interpretable.
The next video clearly explains this fundamental difference.
Regularization Part 2: Lasso (L1) Regression
Now, let's watch 'Regularization Part 2: Lasso (L1) Regression' from StatQuest. It builds directly on the concepts from the Ridge video and highlights the unique feature selection property of Lasso.
Watch the following segments: 00:00 - 02:42: A quick review of Ridge and the introduction of the Lasso penalty. 04:50 - 07:12: This is the most important part. See how Lasso can shrink a coefficient all the way to zero, effectively removing a feature from the model. 07:12 - 07:50: A final summary comparing the two.
4. Geometric Intuition: Why Lasso Performs Feature Selection
You might be wondering why the L1 penalty leads to zero coefficients while the L2 penalty doesn't. A geometric interpretation makes this crystal clear.
Imagine a model with two coefficients, and . Regularization constrains the possible values of these coefficients to a certain "budget."
- Ridge (L2): The constraint is , which defines a circle.
- Lasso (L1): The constraint is , which defines a diamond.
The model tries to find the coefficients within this budget that get closest to the OLS solution (the point that minimizes the RSS). This is like expanding an ellipse (representing the contours of the RSS function) until it just touches the constraint region.

As you can see in the image:
- The circular Ridge constraint is smooth. The ellipse is likely to touch it at a point where neither nor is zero.
- The diamond-shaped Lasso constraint has sharp corners that lie on the axes. The ellipse is very likely to touch one of these corners, forcing one of the coefficients to be exactly zero.
This visual explanation is a powerful way to understand the fundamental difference in behavior between the two methods.
5. Practical Implementation and Comparison
Now that you understand the theory, let's focus on the practical side. How do you choose between Ridge and Lasso, and how do you implement them in Python?
A crucial prerequisite for any regularized linear model is feature scaling. Because the penalty is based on the magnitude of the coefficients, features with larger scales (e.g., house size in square feet) would be unfairly penalized compared to features with smaller scales (e.g., number of rooms). Using StandardScaler from scikit-learn is standard practice.
The following guide provides a concise comparison and a complete Python implementation.
Ridge Regression vs Lasso Regression
This article, 'Ridge Regression vs Lasso Regression', provides a clear, practical comparison and demonstrates how to implement these models using scikit-learn.
Please read from the heading 'Ridge Regression (L2 Regularization)' down to the end of the Python code blocks. Focus on: The loss function definitions for Ridge and Lasso. The section 'Comparing Ridge and Lasso', which summarizes their differences regarding feature selection and handling of correlated features. The 'When to use' guidelines for a practical application scenario. The Python code, noticing the use of StandardScaler, and how Ridge and Lasso are instantiated and fit.
To summarize the key points from the article:
| Aspect | Ridge Regression (L2) | Lasso Regression (L1) |
|---|---|---|
| Penalty | Sum of squared coefficients () | Sum of absolute coefficients ($\lambda\sum |
| Feature Selection | No. Shrinks coefficients but none become zero. | Yes. Can shrink coefficients to exactly zero. |
| Correlated Features | Tends to shrink coefficients for correlated features towards each other. | Tends to arbitrarily pick one feature and zero out the others. |
| Use Case | Good when you believe most features are useful and you want to handle multicollinearity. | Good when you suspect many features are irrelevant and you want a simpler, more interpretable model. |
Here's how you would typically implement them using scikit-learn:
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge, Lasso
from sklearn.model_selection import train_test_split
# Assume X and y are your feature matrix and target vector
# 1. Split data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 2. Scale features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# 3. Fit Ridge model
# alpha is the equivalent of lambda (λ)
ridge_model = Ridge(alpha=1.0)
ridge_model.fit(X_train_scaled, y_train)
print("Ridge Coefficients:", ridge_model.coef_)
# 4. Fit Lasso model
lasso_model = Lasso(alpha=0.1)
lasso_model.fit(X_train_scaled, y_train)
print("Lasso Coefficients:", lasso_model.coef_)
Test your understanding!
Imagine you are a data scientist at a biotech company. You have a dataset with expression levels from 10,000 different genes (features) for 200 patients, and you want to predict a specific health outcome. You suspect that only a small handful of these 10,000 genes are actually relevant to the outcome.
Which regularization technique, Ridge or Lasso, would be a better starting point for this problem, and why?
Show answer
Lasso Regression would be the better choice here.
The key reasons are:
- Sparsity of features: The problem states that you suspect only a "small handful" of the 10,000 genes are relevant. Lasso is designed for this scenario, as its L1 penalty can shrink the coefficients of irrelevant features to exactly zero, performing automatic feature selection.
- Interpretability: By identifying a small subset of influential genes, the resulting model is much easier to interpret and explain to biologists or doctors. A Ridge model would keep all 10,000 genes with non-zero (though small) coefficients, making interpretation nearly impossible.
- High-dimensional data: You have many more features (p=10,000) than samples (n=200). Lasso is particularly well-suited for such
p >> nproblems. While Ridge can also handle this (as mentioned in the bonus part of the StatQuest video LINK), Lasso's feature selection ability makes it more appropriate when sparsity is expected.
Conclusion
Congratulations! You've just learned one of the most important concepts for building robust machine learning models. Regularization is a standard tool for preventing overfitting and improving the generalizability of your models.
Key Takeaways:
- Regularization prevents overfitting by adding a penalty term to the cost function, discouraging large coefficients.
- Ridge Regression (L2) uses a squared penalty (). It shrinks all coefficients towards zero but does not eliminate any features. It's a great general-purpose regularizer.
- Lasso Regression (L1) uses an absolute value penalty (). It can shrink coefficients all the way to zero, performing automatic feature selection and creating sparse, interpretable models.
- The regularization strength is controlled by the hyperparameter (or
alphain scikit-learn), which must be tuned. - Feature scaling is a critical preprocessing step before applying regularized models.
Preview of the Next Lesson:
So far in this module, we have covered Simple Linear Regression, Multiple Linear Regression, Polynomial Regression, and now Ridge and Lasso Regularization. You have the building blocks for creating a variety of powerful regression models. In the next lesson, we will focus on the practical workflow: how to systematically train and evaluate these regression models using scikit-learn. We will consolidate what you've learned and establish a robust framework for building, tuning, and assessing your models' performance.