Regression Modeling: Linear, Regularization & Demand Forecasting

When the target variable is continuous — predicting customer lifetime revenue, real-estate appraisal prices, demand supply quotas, or hospital length of stay — Regression Modeling is the foundational technique. In this class, we master Regularized Regression (Ridge, Lasso, ElasticNet) and residual diagnostics.

Regularization Mathematics: Taming Overfitting

  • Ordinary Least Squares (OLS) Loss: \[ L_{\text{OLS}}(\mathbf{w}) = \frac{1}{n} \sum_{i=1}^{n} (y_i - \mathbf{w}^T \mathbf{x}_i)^2 \]
  • Ridge Regression (\(L_2\) Penalty): Shrinks weights, stabilizes multicollinearity: \[ L_{\text{Ridge}}(\mathbf{w}) = L_{\text{OLS}}(\mathbf{w}) + \alpha \sum_{j=1}^{p} w_j^2 \]
  • Lasso Regression (\(L_1\) Penalty): Produces sparse models via automatic feature selection: \[ L_{\text{Lasso}}(\mathbf{w}) = L_{\text{OLS}}(\mathbf{w}) + \alpha \sum_{j=1}^{p} |w_j| \]

Hands-On Python: Ridge vs. Lasso Benchmarking

import numpy as np
import pandas as pd
from sklearn.linear_model import RidgeCV, LassoCV
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

# Generate correlated dataset with 15 informative and 15 pure noise features
np.random.seed(42)
n_samples, n_features = 500, 30
X = np.random.randn(n_samples, n_features)
true_weights = np.zeros(n_features)
true_weights[:5] = [4.5, -3.2, 2.1, 1.8, -1.2]  # Only first 5 features matter!
y = X @ true_weights + np.random.randn(n_samples) * 0.5

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# Train Lasso with 5-Fold Cross-Validation for optimal alpha
lasso = LassoCV(cv=5).fit(X_train_scaled, y_train)
y_pred = lasso.predict(X_test_scaled)

print(f"Optimal Alpha:     {lasso.alpha_:.4f}")
print(f"Test RMSE:         {np.sqrt(mean_squared_error(y_test, y_pred)):.3f}")
print(f"Test MAE:          {mean_absolute_error(y_test, y_pred):.3f}")
print(f"Test R^2:          {r2_score(y_test, y_pred):.3f}")
print(f"Features Retained: {np.sum(lasso.coef_ != 0)} of {n_features} (Lasso zeroed out {np.sum(lasso.coef_ == 0)} noise features!)")

Residual Analysis for Heteroscedasticity

Always plot model residuals (y_true - y_pred) against predicted values. If residuals form a fan or funnel shape (heteroscedasticity), apply a log or Box-Cox transformation to the target variable to stabilize error variance.

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the difference between Ridge (L2) and Lasso (L1) regularization?

Ridge adds a penalty proportional to the sum of squared weights (alpha * sum(w^2)), shrinking coefficients close to zero without dropping them (ideal for multicollinearity). Lasso adds a penalty proportional to the sum of absolute weights (alpha * sum(|w|)), driving uninformative weights to exact zero and performing automatic feature selection.

Q2. When should I use ElasticNet?

ElasticNet combines both L1 (Lasso) and L2 (Ridge) penalties. It is ideal when you have thousands of features with groups of strongly correlated variables; Lasso arbitrarily picks one feature from a group, whereas ElasticNet retains the whole cluster.

Q3. What is R-squared and Adjusted R-squared?

R-squared measures the proportion of variance in the target explained by the model (0 to 1). However, R-squared automatically increases every time you add ANY new feature, even pure random noise! Adjusted R-squared penalizes redundant features, increasing only if the new feature genuinely improves model predictive power.

Q4. What are the four core assumptions of Linear Regression?

1. Linearity: Target relationship is linear, 2. Homoscedasticity: Residual variance is constant across all predicted values, 3. Normality: Residuals are normally distributed, 4. Independence: Residuals are un-correlated (no autocorrelation in time series).

Q5. Why do we evaluate both MAE and RMSE?

MAE treats all errors with equal linear weight (highly interpretable). RMSE squares errors before averaging, punishing large, catastrophic errors severely. If large prediction misses are extremely costly to your business (e.g., flight overbooking), prioritize minimizing RMSE.

Explore Related Data Science Tutorials & Next Steps

Broaden your statistical analysis, Python data wrangling, and production engineering expertise:

Linear Algebra: OLS Normal Equation

Derive Ordinary Least Squares regression analytically using matrix algebra.

Predictive Modeling Workflow

Implement Ridge, Lasso, and ElasticNet regularization via cross-validation.

Model Evaluation: RMSE, MAE & R2

Evaluate regression performance metrics and residual normality.

Explainable AI (XAI): SHAP Values

Explain individual feature contributions in pricing and demand models.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!