KatInterview

End-to-End Pipeline for Penalized Linear Regression

Machine LearningModel answer
HardModel answerMachine Learningregressionregularizationcross-validation

Last 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:

  1. Preprocessing pipeline: Create a ColumnTransformer that:

    • Scales numeric features (spend, clicks, cpc, plus a time_index derived from date) using StandardScaler
    • Encodes the categorical region with OneHotEncoder(handle_unknown='ignore')
    • Applies PolynomialFeatures(degree=2) to the numeric features only
  2. Target transformation decision: Examine the training target distribution and decide whether to apply a log transformation based on skewness

  3. Cross-validation strategy: Check for temporal autocorrelation in the data. Choose between TimeSeriesSplit (if temporal patterns exist) or standard KFold (if not)

  4. Model selection: Use GridSearchCV to tune and compare Ridge, Lasso, and ElasticNet regression with various regularization strengths

  5. 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
  6. Interpretability: Extract the top 10 most influential features by standardized coefficient magnitude, translating encoded names back to readable form

  7. 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