Lasso Regression
Lasso Regression
A regularized regression technique that performs both shrinkage and automatic feature selection.
What is Lasso Regression?
Lasso Regression (Least Absolute Shrinkage and Selection Operator) is a type of regularized linear regression that adds an L1 penalty to the cost function. It shrinks coefficients and can make some of them exactly zero, effectively performing feature selection.
Why Lasso Regression?
Standard Linear Regression can struggle with:
Linear Regression Problems
- Includes all features (even useless ones)
- Overfits easily
- Cannot perform feature selection
- Sensitive to noise
Lasso Solves It
- Eliminates irrelevant features
- Reduces overfitting
- Performs feature selection
- Simplifies the model
Mathematical Formula
Standard Linear Regression Loss:
Lasso Regression Loss (with L1 penalty):
Where:
- yᵢ = actual value
- ŷᵢ = predicted value
- |bⱼ| = absolute value of feature coefficient
- λ (lambda / alpha) = regularization strength
How Lasso Performs Feature Selection
The L1 penalty creates sharp corners in the cost function. When the optimizer reaches a corner, some coefficients become exactly zero, effectively removing those features from the model.
- Small α → fewer features eliminated.
- Large α → many features eliminated.
- Very large α → all coefficients → 0 (model fails).
Role of α (Alpha / Lambda)
| α Value | Effect | Result |
|---|---|---|
| α = 0 | Same as Linear Regression | No feature selection |
| Small α | Slight shrinkage | Few coefficients near 0 |
| Moderate α | Strong shrinkage | Some coefficients become 0 |
| Large α | Heavy regularization | Many features removed |
| Very Large α | All coefficients become 0 | Useless model |
How Lasso Regression Works
Step-by-Step Process
- Fit a regression model with all features.
- Calculate sum of squared errors (loss).
- Add L1 penalty: λ × Σ|bⱼ|.
- Minimize total loss using coordinate descent.
- Some coefficients become exactly 0 (removed).
- Predict using remaining important features.
Python Example
pip install pandas numpy scikit-learn
import pandas as pd
from sklearn.linear_model import Lasso
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
# Sample dataset
data = {
"Area": [1000, 1500, 2000, 2500, 3000, 3500, 4000],
"Bedrooms": [2, 3, 3, 4, 4, 5, 5],
"Age": [10, 5, 15, 8, 3, 2, 1],
"Garden": [0, 1, 0, 1, 1, 0, 1],
"Price": [40, 55, 65, 80, 100, 120, 140]
}
df = pd.DataFrame(data)
X = df[["Area", "Bedrooms", "Age", "Garden"]]
y = df["Price"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Train Lasso Regression
lasso = Lasso(alpha=1.0)
lasso.fit(X_train, y_train)
# Predict
y_pred = lasso.predict(X_test)
print("Coefficients:", lasso.coef_)
print("Intercept:", lasso.intercept_)
print("MSE:", mean_squared_error(y_test, y_pred))
print("R²:", r2_score(y_test, y_pred))
Comparing Different Alpha Values
for alpha in [0.01, 0.1, 1, 10, 100]:
model = Lasso(alpha=alpha)
model.fit(X_train, y_train)
print(f"Alpha={alpha}, Coefficients={model.coef_}")
Linear vs Lasso Regression
| Aspect | Linear Regression | Lasso Regression |
|---|---|---|
| Regularization | None | L1 (absolute coefficients) |
| Feature Selection | No | Yes (auto) |
| Overfitting | High | Reduced |
| Coefficients | All non-zero | Some become 0 |
Ridge vs Lasso Regression
| Aspect | Ridge (L2) | Lasso (L1) |
|---|---|---|
| Penalty Type | Sum of squared coefficients | Sum of absolute coefficients |
| Shrinkage | Reduces but never zero | Can shrink to exactly zero |
| Feature Selection | No | Yes |
| Best For | Many correlated features | Many irrelevant features |
| Complexity | Stable | Sparse model |
Bias-Variance Tradeoff
Linear Regression
- Low Bias
- High Variance
- Overfits
Lasso Regression
- Higher Bias
- Lower Variance
- Better generalization
Real-Life Analogy
Lasso Regression = Smart Packing
Imagine packing a suitcase for travel. Lasso decides which clothes are essential and discards the rest. Similarly, Lasso Regression keeps only the most useful features and removes unnecessary ones.
Real-World Applications
Finance
- Predict stock returns
- Risk modeling
Healthcare
- Identify important biomarkers
- Predict patient outcomes
Marketing
- Identify top sales drivers
- Customer behavior analysis
Real Estate
- Predict house prices
- Identify important property factors
Genomics
- Identify important genes
- Reduce thousands of features
Big Data
- Handle high-dimensional data
- Eliminate noise features
Advantages
- Performs automatic feature selection.
- Reduces overfitting.
- Simplifies models with many features.
- Easier to interpret due to fewer features.
- Great for high-dimensional datasets.
Disadvantages
Common Mistakes to Avoid
Auto-Tuning with LassoCV
from sklearn.linear_model import LassoCV
lasso_cv = LassoCV(alphas=[0.01, 0.1, 1, 10, 100], cv=5)
lasso_cv.fit(X_train, y_train)
print("Best Alpha:", lasso_cv.alpha_)
print("Best Score:", lasso_cv.score(X_test, y_test))
Best Practices
Quick Tips
- Standardize features before applying Lasso.
- Use LassoCV to find best α automatically.
- Compare Lasso with Ridge and ElasticNet.
- Visualize coefficients to understand selection.
- Use Lasso when features are many and some irrelevant.
- Always validate with cross-validation.
Importance of Lasso Regression
Automatic Feature Selection
- Removes irrelevant features
- Cleaner, simpler model
Reduces Overfitting
- L1 regularization
- Improves generalization
Foundation for ElasticNet
- Combined with Ridge for best of both
- Used in advanced ML pipelines
Better Interpretability
- Shows important predictors
- Easy to explain to stakeholders
Golden Rule
Key Takeaway
Lasso Regression is a powerful regression technique that combines prediction accuracy with automatic feature selection. By using L1 regularization, it builds simpler, faster, and more interpretable models — especially when dealing with high-dimensional or noisy datasets.