Lesson 7 of 9
Comparative Benchmark: Linear, Huber, Ridge, Lasso & Support Vector Regressors
Different regression algorithms embody distinct loss functions and regularization penalties. Ordinary Least Squares minimizes squared L2 error. Ridge minimizes L2 error with an L2 weight penalty. Lasso induces L1 weight sparsity. HuberRegressor minimizes squared error for small residuals and absolute error for large residuals (robust to outliers). Support Vector Regression (SVR) introduces an ε-insensitive loss tube. Benchmarking them systematically exposes their trade-offs.
Comprehensive Multi-Model Regression Benchmark
import numpy as np
import pandas as pd
from sklearn.model_selection import KFold, cross_validate
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet, HuberRegressor
from sklearn.svm import SVR
# Generate regression dataset with correlated features and 5% severe outliers
np.random.seed(42)
n = 1000
p = 15
X = np.random.randn(n, p)
true_beta = np.zeros(p)
true_beta[:5] = [4.0, -3.0, 2.5, -1.5, 1.0] # 5 active features
y = X @ true_beta + np.random.randn(n)
# Inject severe contamination outliers into 5% of targets
outlier_indices = np.random.choice(n, size=50, replace=False)
y[outlier_indices] += np.random.choice([-100.0, 100.0], size=50)
# Candidate model dictionary wrapped in leak-free pipelines
candidate_models = {
'OLS (Baseline)': LinearRegression(),
'Ridge (L2)': Ridge(alpha=10.0),
'Lasso (L1)': Lasso(alpha=0.2),
'ElasticNet': ElasticNet(alpha=0.2, l1_ratio=0.5),
'Huber (Robust)': HuberRegressor(epsilon=1.35, max_iter=300),
'Support Vector (SVR)': SVR(C=1.0, epsilon=0.2)
}
cv = KFold(n_splits=5, shuffle=True, random_state=42)
benchmark_results = []
for name, model in candidate_models.items():
pipe = Pipeline([('scaler', StandardScaler()), ('reg', model)])
scores = cross_validate(pipe, X, y, cv=cv, scoring=['neg_mean_absolute_error', 'neg_root_mean_squared_error'])
mae = -scores['test_neg_mean_absolute_error'].mean()
rmse = -scores['test_neg_root_mean_squared_error'].mean()
benchmark_results.append({
'Algorithm': name,
'5-Fold CV MAE': f"{mae:.2f}",
'5-Fold CV RMSE': f"{rmse:.2f}",
'Outlier Robustness': 'HIGH' if name in ['Huber (Robust)', 'Support Vector (SVR)'] else 'LOW'
})
print("=== MULTI-ALGORITHM REGRESSION BENCHMARK UNDER OUTLIERS ===")
print(pd.DataFrame(benchmark_results).to_string())Pro Tip: When to Deploy HuberRegressor
Whenever your target variable represents financial figures, supply chain lead times, or network latencies containing corrupted measurements, standard OLS and Ridge will be heavily distorted by the outliers. `HuberRegressor` achieves near-optimal OLS performance on clean Gaussian data while remaining immune to extreme leverage points.
MlComparingRegressionAlgorithms Visual Representation
Hands-On Challenge: Compare Kernel Ridge vs Support Vector Regression
Train a `KernelRidge(kernel='rbf')` and `SVR(kernel='rbf')` on a non-linear sinusoidal function corrupted with impulse noise. Compare their training runtimes and test MAEs.
Quick Quiz & Key Concept Checks
Common Pitfall: Comparing Algorithms on a Single Train-Test Split
A single train-test split has high variance. One algorithm may score 5% higher purely because the test set happened to include or exclude a specific outlier. Always report mean ± standard deviation across 5-fold or 10-fold cross-validation.