Python / Python Mathematical Intuition and Scikit Learn Interview Questions
Why must features be standardized before applying Ridge or Lasso regularization, mathematically?
Ridge and Lasso add a penalty proportional to coefficient magnitude — λΣβⱼ² or λΣ|βⱼ| respectively. The magnitude of a coefficient βⱼ is inversely related to the scale of its corresponding feature: if feature j is measured in millions (e.g. company revenue) its coefficient will naturally be tiny, while a feature measured in single digits (e.g. years of experience) will need a much larger coefficient to have comparable predictive impact. Without standardization, the penalty term unfairly penalises features on small scales (which need large coefficients) far more than features on large scales (which need small coefficients), regardless of their actual importance to the prediction.
After standardizing all features to have mean 0 and standard deviation 1, every coefficient represents "effect per one standard deviation change" on a comparable scale, so the regularization penalty treats all features fairly based on their actual predictive contribution rather than an arbitrary measurement unit.
from sklearn.linear_model import Ridge from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline # WRONG: regularizing on raw, unscaled features ridge_unscaled = Ridge(alpha=1.0).fit(X_train, y_train) print('Unscaled coefficients:', ridge_unscaled.coef_) # A revenue-in-dollars feature might get coef ~0.00001 # A years-of-experience feature might get coef ~500 # The penalty unfairly shrinks the experience coefficient much more # CORRECT: always scale before regularized linear models pipeline = Pipeline([ ('scaler', StandardScaler()), ('ridge', Ridge(alpha=1.0)), ]) pipeline.fit(X_train, y_train) scaled_coefs = pipeline.named_steps['ridge'].coef_ print('Scaled coefficients (comparable):', scaled_coefs) # Note: scikit-learn's LinearRegression and tree models don't # need this â only penalized linear models (Ridge, Lasso, ElasticNet)
More Related questions...