1
---
2
name: Regression Modeling
3
description: Build predictive models using linear regression, polynomial regression, and regularized regression for continuous prediction, trend forecasting, and relationship quantification
4
---
5
6
# Regression Modeling
7
8
## Overview
9
10
Regression modeling predicts continuous target values based on input features, establishing quantitative relationships between variables for forecasting and analysis.
11
12
## When to Use
13
14
- Predicting sales, prices, or other continuous numerical outcomes
15
- Understanding relationships between independent and dependent variables
16
- Forecasting trends based on historical data
17
- Quantifying the impact of features on a target variable
18
- Building baseline models for comparison with more complex algorithms
19
- Identifying which variables most influence predictions
20
21
## Regression Types
22
23
- **Linear Regression**: Straight-line fit to data
24
- **Polynomial Regression**: Non-linear relationships
25
- **Ridge (L2)**: Regularization to prevent overfitting
26
- **Lasso (L1)**: Feature selection through regularization
27
- **ElasticNet**: Combines Ridge and Lasso
28
- **Robust Regression**: Resistant to outliers
29
30
## Key Metrics
31
32
- **R² Score**: Proportion of variance explained
33
- **RMSE**: Root Mean Squared Error
34
- **MAE**: Mean Absolute Error
35
- **AIC/BIC**: Model comparison criteria
36
37
## Implementation with Python
38
39
```python
40
import pandas as pd
41
import numpy as np
42
import matplotlib.pyplot as plt
43
from sklearn.linear_model import (
44
LinearRegression, Ridge, Lasso, ElasticNet, HuberRegressor
45
)
46
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
47
from sklearn.model_selection import train_test_split, cross_val_score
48
from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
49
import seaborn as sns
50
51
# Generate sample data
52
np.random.seed(42)
53
X = np.random.uniform(0, 100, 200).reshape(-1, 1)
54
y = 2.5 * X.squeeze() + 30 + np.random.normal(0, 50, 200)
55
56
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
57
58
# Linear Regression
59
lr_model = LinearRegression()
60
lr_model.fit(X_train, y_train)
61
y_pred_lr = lr_model.predict(X_test)
62
63
print("Linear Regression:")
64
print(f" R² Score: {r2_score(y_test, y_pred_lr):.4f}")
65
print(f" RMSE: {np.sqrt(mean_squared_error(y_test, y_pred_lr)):.4f}")
66
print(f" Coefficient: {lr_model.coef_[0]:.4f}")
67
print(f" Intercept: {lr_model.intercept_:.4f}")
68
69
# Polynomial Regression (degree 2)
70
poly = PolynomialFeatures(degree=2)
71
X_train_poly = poly.fit_transform(X_train)
72
X_test_poly = poly.transform(X_test)
73
74
poly_model = LinearRegression()
75
poly_model.fit(X_train_poly, y_train)
76
y_pred_poly = poly_model.predict(X_test_poly)
77
78
print("\nPolynomial Regression (degree=2):")
79
print(f" R² Score: {r2_score(y_test, y_pred_poly):.4f}")
80
print(f" RMSE: {np.sqrt(mean_squared_error(y_test, y_pred_poly)):.4f}")
81
82
# Ridge Regression (L2 regularization)
83
ridge_model = Ridge(alpha=1.0)
84
ridge_model.fit(X_train, y_train)
85
y_pred_ridge = ridge_model.predict(X_test)
86
87
print("\nRidge Regression (alpha=1.0):")
88
print(f" R² Score: {r2_score(y_test, y_pred_ridge):.4f}")
89
print(f" RMSE: {np.sqrt(mean_squared_error(y_test, y_pred_ridge)):.4f}")
90
91
# Lasso Regression (L1 regularization)
92
lasso_model = Lasso(alpha=0.1)
93
lasso_model.fit(X_train, y_train)
94
y_pred_lasso = lasso_model.predict(X_test)
95
96
print("\nLasso Regression (alpha=0.1):")
97
print(f" R² Score: {r2_score(y_test, y_pred_lasso):.4f}")
98
print(f" RMSE: {np.sqrt(mean_squared_error(y_test, y_pred_lasso)):.4f}")
99
100
# ElasticNet Regression
101
elastic_model = ElasticNet(alpha=0.1, l1_ratio=0.5)
102
elastic_model.fit(X_train, y_train)
103
y_pred_elastic = elastic_model.predict(X_test)
104
105
print("\nElasticNet Regression:")
106
print(f" R² Score: {r2_score(y_test, y_pred_elastic):.4f}")
107
print(f" RMSE: {np.sqrt(mean_squared_error(y_test, y_pred_elastic)):.4f}")
108
109
# Robust Regression (resistant to outliers)
110
huber_model = HuberRegressor(max_iter=1000, alpha=0.1)
111
huber_model.fit(X_train, y_train)
112
y_pred_huber = huber_model.predict(X_test)
113
114
print("\nHuber Regression (Robust):")
115
print(f" R² Score: {r2_score(y_test, y_pred_huber):.4f}")
116
print(f" RMSE: {np.sqrt(mean_squared_error(y_test, y_pred_huber)):.4f}")
117
118
# Visualization
119
fig, axes = plt.subplots(2, 3, figsize=(15, 8))
120
121
models_data = [
122
(X_test, y_test, y_pred_lr, 'Linear'),
123
(X_test_poly, y_test, y_pred_poly, 'Polynomial (deg=2)'),
124
(X_test, y_test, y_pred_ridge, 'Ridge'),
125
(X_test, y_test, y_pred_lasso, 'Lasso'),
126
(X_test, y_test, y_pred_elastic, 'ElasticNet'),
127
(X_test, y_test, y_pred_huber, 'Huber'),
128
]
129
130
for idx, (X_p, y_t, y_p, label) in enumerate(models_data):
131
if label in ['Polynomial (deg=2)']:
132
x_plot = X_p[:, 1] # Use quadratic feature for plotting
133
else:
134
x_plot = X_p
135
136
ax = axes[idx // 3, idx % 3]
137
ax.scatter(x_plot, y_t, alpha=0.5, label='Actual')
138
ax.scatter(x_plot, y_p, alpha=0.5, color='red', label='Predicted')
139
ax.set_title(f'{label}\nR²={r2_score(y_t, y_p):.4f}')
140
ax.legend()
141
ax.grid(True, alpha=0.3)
142
143
plt.tight_layout()
144
plt.show()
145
146
# Residual analysis
147
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
148
149
residuals = y_test - y_pred_lr
150
axes[0].scatter(y_pred_lr, residuals, alpha=0.5)
151
axes[0].axhline(y=0, color='r', linestyle='--')
152
axes[0].set_title('Residual Plot')
153
axes[0].set_xlabel('Fitted Values')
154
axes[0].set_ylabel('Residuals')
155
156
axes[1].hist(residuals, bins=20, edgecolor='black')
157
axes[1].set_title('Residuals Distribution')
158
axes[1].set_xlabel('Residuals')
159
axes[1].set_ylabel('Frequency')
160
161
plt.tight_layout()
162
plt.show()
163
164
# Cross-validation
165
cv_scores = cross_val_score(LinearRegression(), X, y, cv=5, scoring='r2')
166
print(f"\nCross-validation R² scores: {cv_scores}")
167
print(f"Mean CV R²: {cv_scores.mean():.4f} (+/- {cv_scores.std():.4f})")
168
169
# Regularization parameter tuning
170
alphas = np.logspace(-3, 3, 100)
171
ridge_scores = []
172
173
for alpha in alphas:
174
ridge = Ridge(alpha=alpha)
175
scores = cross_val_score(ridge, X_train, y_train, cv=5, scoring='r2')
176
ridge_scores.append(scores.mean())
177
178
best_alpha_idx = np.argmax(ridge_scores)
179
best_alpha = alphas[best_alpha_idx]
180
181
plt.figure(figsize=(10, 5))
182
plt.semilogx(alphas, ridge_scores)
183
plt.axvline(x=best_alpha, color='red', linestyle='--', label=f'Best alpha={best_alpha:.4f}')
184
plt.xlabel('Alpha (Regularization Strength)')
185
plt.ylabel('Cross-validation R² Score')
186
plt.title('Ridge Regression: Alpha Tuning')
187
plt.legend()
188
plt.grid(True, alpha=0.3)
189
plt.show()
190
191
# Feature importance (coefficients)
192
if hasattr(lr_model, 'coef_'):
193
print(f"\nModel Coefficients: {lr_model.coef_}")
194
195
# Additional evaluation and diagnostics
196
197
# Model prediction intervals
198
from scipy import stats as sp_stats
199
200
predictions = lr_model.predict(X_test)
201
residuals = y_test - predictions
202
mse = np.mean(residuals**2)
203
rmse = np.sqrt(mse)
204
205
# Prediction intervals (95%)
206
n = len(X_test)
207
p = X_test.shape[1]
208
dof = n - p - 1
209
t_val = sp_stats.t.ppf(0.975, dof)
210
margin = t_val * np.sqrt(mse * (1 + 1/n))
211
pred_intervals = np.column_stack([
212
predictions - margin,
213
predictions + margin
214
])
215
216
print(f"\nPrediction Intervals (95%):")
217
print(f"First prediction: {predictions[0]:.2f} [{pred_intervals[0, 0]:.2f}, {pred_intervals[0, 1]:.2f}]")
218
219
# Variance inflation factors for multicollinearity
220
from statsmodels.stats.outliers_influence import variance_inflation_factor
221
222
vif_data = pd.DataFrame()
223
vif_data["Feature"] = X_test.columns if hasattr(X_test, 'columns') else range(X_test.shape[1])
224
try:
225
vif_data["VIF"] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]
226
print("\nVariance Inflation Factor (VIF):")
227
print(vif_data)
228
except:
229
print("VIF calculation skipped (insufficient features)")
230
231
# Prediction by group/segment
232
if hasattr(X_test, 'columns'):
233
segment_results = {}
234
for feat in X_test.columns[:2]:
235
q1, q3 = X_test[feat].quantile([0.25, 0.75])
236
low = X_test[X_test[feat] <= q1]
237
high = X_test[X_test[feat] >= q3]
238
239
if len(low) > 0 and len(high) > 0:
240
low_pred_rmse = np.sqrt(np.mean((y_test[low.index] - lr_model.predict(low))**2))
241
high_pred_rmse = np.sqrt(np.mean((y_test[high.index] - lr_model.predict(high))**2))
242
segment_results[feat] = {
243
'Low RMSE': low_pred_rmse,
244
'High RMSE': high_pred_rmse,
245
}
246
247
if segment_results:
248
print(f"\nSegment Performance:")
249
for feat, results in segment_results.items():
250
print(f" {feat}: Low={results['Low RMSE']:.2f}, High={results['High RMSE']:.2f}")
251
252
print("\nRegression model evaluation complete!")
253
```
254
255
## Assumption Checking
256
257
- **Linearity**: Relationship is linear
258
- **Independence**: Observations are independent
259
- **Homoscedasticity**: Constant variance of errors
260
- **Normality**: Errors are normally distributed
261
- **No multicollinearity**: Features not highly correlated
262
263
## Model Selection
264
265
- **Simple data**: Linear regression
266
- **Non-linear patterns**: Polynomial regression
267
- **Many features**: Lasso or ElasticNet
268
- **Outliers**: Robust regression
269
- **Prevent overfitting**: Ridge or ElasticNet
270
271
## Deliverables
272
273
- Fitted models with coefficients
274
- R² and RMSE metrics
275
- Residual plots and analysis
276
- Cross-validation results
277
- Regularization parameter tuning curves
278
- Model comparison summary
279
- Predictions with confidence intervals
280