End-to-End Pipeline for Penalized Linear Regression
Machine LearningModel answerLast updated
Build a complete scikit-learn pipeline with preprocessing, regularization, proper validation, and interpretation for predicting marketing signups.
You have marketing data with features: spend, clicks, cpc (cost-per-click), region (categorical), and date. The target is signups. Your task is to build a production-ready regression pipeline that predicts signups.
Implement the following in scikit-learn:
-
Preprocessing pipeline: Create a
ColumnTransformerthat:- Scales numeric features (
spend,clicks,cpc, plus atime_indexderived fromdate) usingStandardScaler - Encodes the categorical
regionwithOneHotEncoder(handle_unknown='ignore') - Applies
PolynomialFeatures(degree=2)to the numeric features only
- Scales numeric features (
-
Target transformation decision: Examine the training target distribution and decide whether to apply a log transformation based on skewness
-
Cross-validation strategy: Check for temporal autocorrelation in the data. Choose between
TimeSeriesSplit(if temporal patterns exist) or standardKFold(if not) -
Model selection: Use
GridSearchCVto tune and compare Ridge, Lasso, and ElasticNet regression with various regularization strengths -
Evaluation:
- Create a chronological train/test split (80/20) before any other operations
- Use nested cross-validation to get an unbiased estimate of the tuning process
- Report RMSE and R² on the held-out test set
-
Interpretability: Extract the top 10 most influential features by standardized coefficient magnitude, translating encoded names back to readable form
-
Persistence: Save the final model and demonstrate reloading it to score new data
Explain your design choices and how you prevent data leakage. Use RMSE as your primary metric.
Hints
Hint 1
All data-dependent operations (scaling, encoding, date reference) must happen inside the pipeline to avoid leakage
Hint 2
For time-series data, a chronological split is more realistic than random splitting
Hint 3
Scaling before and after polynomial expansion ensures regularization treats all features equally
Hint 4
When using log-transformed targets, predictions are still on the original scale but the model optimizes a different objective
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Penalized Regression Pipeline
Core Architecture
The solution centers on strict leakage prevention: every transformation that depends on data statistics must be learned within cross-validation folds. This is achieved by packaging all preprocessing and modeling into a single Pipeline, then wrapping it in GridSearchCV.
Three-Level Evaluation Strategy
- Nested cross-validation score: Provides an unbiased estimate of the entire hyperparameter search process
- Test set performance: Final reality check on completely unseen data, measured once
- Best inner CV score: Reported for context but optimistically biased due to hyperparameter optimization
Design Decisions with Rationale
Chronological 80/20 split: Marketing data contains temporal trends. The model must predict future performance from past data. Random splitting allows the model to interpolate between adjacent time periods, artificially inflating validation scores. Split on date percentiles instead.
Time indexer as a fitted transformer: Converting dates to "days since start" requires establishing a reference point. This reference must be learned from training data and applied consistently at inference time. Implement a custom transformer that stores origin_ during fit() and applies it in transform().
Two-stage scaling around polynomial expansion:
- First
StandardScaler: Prevents numerical overflow when squaring features PolynomialFeatures(degree=2): Creates interaction and quadratic terms from numeric features only- Second
StandardScaler: Gives every expanded feature unit variance, so L1/L2 penalties treat them equally and coefficients become interpretable as "per-standard-deviation" effects
OneHotEncoder without dropping: Set handle_unknown='ignore' so unseen regions at inference time map to the baseline (all zeros) rather than causing errors. Regularization eliminates the need to drop a reference level, and keeping all levels makes each dummy coefficient directly interpretable.
Log transformation diagnostic: Marketing signup counts are typically right-skewed. Compute scipy.stats.skew() on the training target. If skew > 1.0 and all values are non-negative, wrap the pipeline in TransformedTargetRegressor(func=np.log1p, inverse_func=np.expm1). This models log-space relationships while keeping predictions and RMSE on the original scale. Note: predicting the mean in log-space then exponentiating approximates the median, not the mean—acceptable for this use case.
Temporal autocorrelation check: Aggregate training signups by date and compute lag-1 autocorrelation ρ₁. If |ρ₁| > 2/√n (approximate 95% confidence band for white noise), use TimeSeriesSplit(n_splits=5). Otherwise use KFold(5, shuffle=True) for better data efficiency.
Why all three regularizers:
- Ridge: Handles collinearity (spend ≈ clicks × cpc) by shrinking correlated coefficients together
- Lasso: Performs feature selection among the ~14 polynomial terms
- ElasticNet: Combines both behaviors
Use a single GridSearchCV with multiple parameter dictionaries to swap the estimator type. Test Ridge with α ∈ [10⁻³, 10³], Lasso with α ∈ [10⁻⁴, 1], and ElasticNet with those α values plus l1_ratio ∈ {0.2, 0.5, 0.8}.
RMSE vs R²: RMSE is in signup units (interpretable to stakeholders) and heavily penalizes large errors. R² provides context about variance explained but can be misleading with transformed targets.
Computational Complexity
With 4 numeric features expanding to 14 polynomial terms plus R region dummies (total p = 14 + R features):
- Ridge: O(np² + p³) per fit via normal equations
- Lasso/ElasticNet: O(np × iterations) via coordinate descent
Total model fits ≈ 26 grid points × 5 inner folds × 6 outer evaluations ≈ 780 fits, each fast for typical marketing dataset sizes (n < 100k).
Feature Interpretation
After selecting the best model, extract model.named_steps['model'].coef_ (or regressor.regressor.named_steps['model'].coef_ if using transformed target). These are standardized coefficients: the change in (log-)signups per standard deviation increase in each feature.
Map feature indices back to names using ColumnTransformer.get_feature_names_out(). For polynomial features, names look like "num__x0 x1" (interaction) or "num__x2^2" (quadratic). For one-hot features: "cat__region_west". Sort by absolute value and report the top 10.
Edge Cases
- Date boundaries in TimeSeriesSplit: Rows from the same date can span fold boundaries. For strict temporal separation, split on unique dates rather than rows.
- Convergence warnings: Set
max_iter=50000for Lasso/ElasticNet to avoid premature stopping with small α values. - Zero clicks: Would make
cpcundefined. Assert this was handled in data cleaning. - Custom transformer serialization: The
TimeIndexerclass must be importable when reloading the model. Define it in a module, not in__main__.
Implementation Outline
import numpy as np
import pandas as pd
import joblib
from scipy.stats import skew
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.compose import ColumnTransformer, TransformedTargetRegressor
from sklearn.preprocessing import StandardScaler, OneHotEncoder, PolynomialFeatures
from sklearn.pipeline import Pipeline
from sklearn.linear_model import Ridge, Lasso, ElasticNet
from sklearn.model_selection import GridSearchCV, KFold, TimeSeriesSplit, cross_val_score
from sklearn.metrics import mean_squared_error, r2_score
class TimeIndexer(BaseEstimator, TransformerMixin):
def __init__(self, date_col="date"):
self.date_col = date_col
def fit(self, X, y=None):
self.origin_ = pd.to_datetime(X[self.date_col]).min()
return self
def transform(self, X):
X = X.copy()
X["time_index"] = (pd.to_datetime(X[self.date_col]) - self.origin_).dt.days
return X
# Load and chronologically split
df = pd.read_csv("data.csv", parse_dates=["date"]).sort_values("date")
cutoff_date = df["date"].quantile(0.8)
train_df = df[df["date"] <= cutoff_date]
test_df = df[df["date"] > cutoff_date]
X_train = train_df[["date", "spend", "clicks", "cpc", "region"]]
y_train = train_df["signups"]
X_test = test_df[["date", "spend", "clicks", "cpc", "region"]]
y_test = test_df["signups"]
# Diagnostics on training data only
use_log_transform = (skew(y_train) > 1.0) and (y_train.min() >= 0)
daily_signups = train_df.groupby("date")["signups"].sum()
autocorr = daily_signups.autocorr(lag=1)
use_timeseries_split = abs(autocorr) > 2 / np.sqrt(len(daily_signups))
cv_splitter = TimeSeriesSplit(n_splits=5) if use_timeseries_split else KFold(5, shuffle=True, random_state=42)
# Build pipeline
numeric_pipeline = Pipeline([
("scale1", StandardScaler()),
("poly", PolynomialFeatures(degree=2, include_bias=False)),
("scale2", StandardScaler())
])
preprocessor = ColumnTransformer([
("numeric", numeric_pipeline, ["spend", "clicks", "cpc", "time_index"]),
("categorical", OneHotEncoder(handle_unknown="ignore"), ["region"])
])
base_pipeline = Pipeline([
("time_index", TimeIndexer()),
("preprocess", preprocessor),
("model", Ridge())
])
if use_log_transform:
pipeline = TransformedTargetRegressor(
regressor=base_pipeline,
func=np.log1p,
inverse_func=np.expm1
)
param_prefix = "regressor__model"
else:
pipeline = base_pipeline
param_prefix = "model"
# Hyperparameter grid
param_grid = [
{param_prefix: [Ridge()], f"{param_prefix}__alpha": np.logspace(-3, 3, 7)},
{param_prefix: [Lasso(max_iter=50000)], f"{param_prefix}__alpha": np.logspace(-4, 0, 5)},
{param_prefix: [ElasticNet(max_iter=50000)],
f"{param_prefix}__alpha": np.logspace(-4, 0, 5),
f"{param_prefix}__l1_ratio": [0.2, 0.5, 0.8]}
]
# Grid search with nested CV
grid_search = GridSearchCV(
pipeline, param_grid,
cv=cv_splitter,
scoring="neg_root_mean_squared_error",
n_jobs=-1
)
# Nested CV score
nested_scores = cross_val_score(
grid_search, X_train, y_train,
cv=cv_splitter,
scoring="neg_root_mean_squared_error"
)
print(f"Nested CV RMSE: {-nested_scores.mean():.2f} ± {nested_scores.std():.2f}")
# Fit on full training set
grid_search.fit(X_train, y_train)
print(f"Best params: {grid_search.best_params_}")
print(f"Best inner CV RMSE: {-grid_search.best_score_:.2f}")
# Test set evaluation
y_pred = grid_search.predict(X_test)
test_rmse = mean_squared_error(y_test, y_pred, squared=False)
test_r2 = r2_score(y_test, y_pred)
print(f"Test RMSE: {test_rmse:.2f}, R²: {test_r2:.3f}")
# Feature importance
best_model = grid_search.best_estimator_
if use_log_transform:
coefs = best_model.regressor_.named_steps["model"].coef_
feature_names = best_model.regressor_.named_steps["preprocess"].get_feature_names_out()
else:
coefs = best_model.named_steps["model"].coef_
feature_names = best_model.named_steps["preprocess"].get_feature_names_out()
feature_importance = pd.DataFrame({
"feature": feature_names,
"coefficient": coefs,
"abs_coefficient": np.abs(coefs)
}).sort_values("abs_coefficient", ascending=False)
print("\nTop 10 features:")
print(feature_importance.head(10))
# Save and reload
joblib.dump(grid_search.best_estimator_, "model.pkl")
loaded_model = joblib.load("model.pkl")
new_predictions = loaded_model.predict(X_test.head(5))
print(f"Sample predictions: {new_predictions}")
Common Mistakes to Avoid
- Fitting transformers on the full dataset before splitting (leaks test statistics)
- Using random splitting for time-series data
- Forgetting to re-scale after polynomial expansion (unequal regularization)
- Not handling unknown categories at inference time
- Reporting only the inner CV score (optimistically biased)
- Applying log transform without checking for negative values
- Comparing coefficients across differently-scaled features