- Learn
- Computer Science & IT
- Data Science & AI
- Machine Learning
- Regularization and Feature Engineering
Regularization and Feature Engineering
IntermediateLesson 5 of 9 in Machine Learning Course
What you will learn
- Use training and validation error to tell whether a model is too simple or too flexible, and explain how a penalty added to the cost function controls that flexibility.
- Tell overfitting from underfittingCompare training and validation error to recognize a model that is too simple, too flexible or about right, and connect each pattern to bias and variance.
- Control model flexibility with a penaltyChoose a remedy for overfitting or underfitting, and explain how a regularization term in the cost function shrinks the weights, with λ setting the trade-off.
- Tell overfitting from underfitting
- Fit penalized linear models, explain how the L2 and L1 penalties shrink coefficients differently, regularize classifiers, and choose the penalty strength with cross-validation.
- Fit and interpret ridge regressionWrite the ridge objective, show how the L2 penalty shrinks coefficients toward zero, and explain why ridge needs standardized features and helps with correlated features.
- Build sparse models with the lassoWrite the lasso objective, explain why the L1 penalty sets some coefficients exactly to zero, and judge when a sparse model is the better choice.
- Combine penalties and regularize classifiersUse elastic net to mix the L1 and L2 penalties, and control the regularization of logistic regression through its inverse strength C.
- Tune the penalty strength with cross-validationSearch a logarithmic grid of penalty values with cross-validation, read coefficient paths, and pick a value with the minimum-error or one-standard-error rule without touching the test set.
- Fit and interpret ridge regression
- Compare subset, stepwise, filter and embedded ways to choose features, judge models of different sizes fairly, and keep every selection step inside the validation loop.
- Search for good feature subsetsExplain best subset and stepwise selection, count the models they fit, and compare models of different sizes with adjusted criteria or cross-validation.
- Use filter and embedded selection without leakageApply variance and univariate filters and model-based selection, and keep selection inside cross-validation so the performance estimate stays honest.
- Search for good feature subsets
- Turn raw columns into numeric features a model can use: encode categories, build new features from existing ones, and put numeric features on suitable scales and shapes.
- Encode categorical variablesChoose one-hot, ordinal or target encoding for nominal, ordered and high-cardinality categories, and handle the dummy-variable trap and categories never seen in training.
- Create new features from existing onesBuild polynomial, interaction, ratio, binned and date-time features that let a model express the pattern, and keep their number and their information honest.
- Scale and transform numeric featuresDecide when scaling matters, apply standardization, min-max and robust scaling and log or power transforms, and learn every transformation from the training data only.
- Encode categorical variables
- Handle missing values and chain every preprocessing step with the model in one pipeline that is fitted, tuned, evaluated and reused on new data without leakage.
- Handle missing valuesRecognize how values went missing, compare deletion, simple and model-based imputation and missing-value indicators, and learn imputation from the training data only.
- Chain preprocessing and model with Pipeline and ColumnTransformerCombine imputation, encoding, scaling and the model in one object, apply different steps to numeric and categorical columns, and cross-validate the whole chain.
- Tune, evaluate and reuse the whole pipelineTune preprocessing and model settings together with grid search, evaluate the final pipeline once on the test set, and make the result reproducible and reusable on new data.
- Handle missing values
Regularization and Feature Engineering study guide
1Diagnose overfitting and underfitting
A model can learn the training data well and still make poor predictions. Training and validation errors show whether extra flexibility helps or starts fitting noise. Reading those errors against a baseline gives you a reason to simplify a model, enrich its inputs, or change its penalty. Regularization puts that choice into the training objective, so the fitted weights must balance a close fit against their size.
1.1 Read training and validation errors
A low training error tells you that the model fits familiar rows. Generalization asks how well it predicts rows that were held out during fitting. Because training directly minimizes the training loss, that loss gives an optimistic picture of future performance.
Compare both errors with a baseline
A baseline makes the error scale meaningful. For regression, always predicting the training mean is one useful baseline; for classification, predicting the most common class is another.
Consider three polynomial models fitted to the same noisy curved data. The mean-prediction baseline has RMSE 5.0.
| Polynomial degree | Training RMSE | Validation RMSE | Reading |
|---|---|---|---|
| 1 | 4.1 | 4.3 | Too simple for this pattern |
| 4 | 1.9 | 2.1 | Useful fit that transfers |
| 15 | 0.4 | 7.8 | Fits training noise |
Degree 1 makes fairly large errors on both sets. Degree 4 uses the same input and cuts validation error substantially, confirming that degree 1 underfits. Degree 15 nearly memorizes the training data, yet predicts worse than the baseline on validation data: it overfits.
High, similar errors alone do not identify the cause. If more flexible models cannot improve them, the inputs may contain little useful signal. Better measurements or features can then matter more than a larger model. Likewise, a small training–validation gap is useful only when the errors themselves are acceptable.
Connect flexibility to bias and variance
Model complexity, or capacity, is the range of patterns a model can represent. Higher polynomial degree, more input features, deeper trees, and a smaller neighbor count in k-nearest neighbors can all increase flexibility. As flexibility rises, training error usually falls. Validation error often falls at first, reaches a minimum, and then rises as the model starts following noise.
Bias comes from simplifying assumptions that miss the real pattern. Variance describes how much the fitted model would change across different training samples. At a fixed input, expected squared prediction error decomposes as:
The noise variance is irreducible error in this decomposition. Extra flexibility can reduce bias while increasing variance. Underfitting usually points to high bias; overfitting points to high variance. Validation checks the combined result, which is why minimizing training error is not enough.
For classification, compare the same kind of evidence. A spam filter with 99% training accuracy and 81% validation accuracy shows a large generalization gap. Accuracies of 72% and 71% look close, but add little if the majority-class baseline already reaches 70%. If a more flexible model on the same inputs reaches 85% validation accuracy, the simpler classifier underfits.
Use learning curves to choose a remedy
Learning curves plot training and validation error against the number of training rows. High curves that level off close together suggest that more rows alone will do little: the model still cannot express the pattern. A large gap that narrows as rows are added suggests that more data can reduce variance. Repeatedly choosing settings against one validation set can also overfit that set, so keep the test set untouched for the final evaluation.
Key Takeaways
- Judge training and validation errors against a meaningful baseline.
- Underfitting misses a pattern that a more flexible model can learn from the same inputs.
- Overfitting combines a close training fit with poor performance on held-out data.
- Bias, variance, and irreducible noise all contribute to prediction error.
- Learning curves help distinguish a need for more data from a need for more flexibility.
1.2 Make large weights costly
Regularization adds a charge for large weights to the training loss. The model can still fit the data, but a small improvement in fit must justify the weight size needed to achieve it. This often reduces the variance of a flexible model.
Balance fit and weight size
For linear regression with rows and features, an L2-regularized cost is:
The first term measures prediction error. The second adds the squared weights and multiplies that total by the nonnegative penalty strength . The intercept is left out: it sets the overall prediction level, and penalizing it would pull predictions toward zero.
With four prediction errors , the squared errors sum to 6. Dividing by gives a fit term of 0.75. For weights and , the squared weights sum to 13, so the penalty is . The total cost is . A candidate with slightly worse fit but much smaller weights can have a lower total cost.
Set the amount of shrinkage
With , the penalty vanishes. Increasing it puts more pressure on the weights to shrink. Very strong regularization makes the slopes close to zero and predictions nearly constant, which can cause underfitting. Choose the strength by validation, not by comparing training objectives across strengths: turning off a nonnegative penalty always makes that objective easier to minimize.
| Diagnosis | Useful changes |
|---|---|
| Overfitting | More training rows, fewer features, a simpler model, or stronger regularization |
| Underfitting | Better features, greater model flexibility, or weaker regularization |
L2 shrinks weights and generally keeps all features. L1 charges absolute weight size and can set weights exactly to zero, selecting features during fitting. Both depend on feature units, so put numeric features on comparable scales.
See the change in gradient descent
Let be the learning rate. The L2 weight update becomes:
The extra factor shrinks the existing weight before the usual error-gradient contribution. With , , and , it is . The intercept update has no shrinkage term. This repeated multiplication is the weight-decay interpretation of L2 regularization.
Apply the same idea to a classifier
For binary logistic regression, replace the squared-error fit term by log loss:
Adding the same L2 term discourages large slopes and overly contorted boundaries built from many polynomial features. The regularized gradient has the same error-times-input form.
Parameter names change in software. In these formulas, is a learning rate. In scikit-learn, Ridge, Lasso, and ElasticNet call their penalty strength alpha. LogisticRegression uses inverse strength C: decreasing C strengthens regularization.
Key Takeaways
- Regularization balances prediction loss with a penalty on weight size.
- The intercept is normally excluded from the penalty.
- A larger penalty can reduce overfitting, but too much can cause underfitting.
- L2 shrinks weights; L1 can also select features by producing zeros.
- In scikit-learn, larger alpha and smaller C mean stronger regularization.
- Scale features before fitting a penalized linear model.
2Shrink coefficients with ridge, lasso and elastic net
Ridge, lasso, and elastic net all trade some training fit for smaller coefficients, but they do not produce the same kind of model. Their penalties behave differently near zero and when inputs are strongly correlated. Matching a penalty to the data is only part of the job: its strength must also be selected on held-out folds, with preprocessing refitted in each fold. Coefficient paths and validation errors help explain the resulting choice.
2.1 Stabilize a linear model with ridge
Ridge regression adds an L2 penalty to the residual sum of squares, or RSS. It is useful when ordinary least-squares coefficients are unstable, especially with correlated inputs or many features relative to the number of rows.
Read the objective
With slope coefficients, ridge minimizes:
The intercept is unpenalized. An equivalent view is to minimize RSS while keeping . The budget limits total squared coefficient size; a tighter budget corresponds to stronger shrinkage.
At zero penalty, ridge reduces to least squares. Increasing the penalty generally moves the coefficients toward zero without setting them exactly to zero. As the penalty becomes extremely large, all slopes approach zero and the prediction approaches the training target mean when the intercept is fitted.
Work through a single slope
For a model without an intercept, use and . The cross-product sum is and the squared-input sum is . Least squares gives slope .
Ridge adds the penalty strength to the denominator:
At , the slope is . At , it is . The original points lie perfectly on a slope of 2; ridge deliberately accepts training error to reduce sensitivity to the particular sample.
Why correlated features benefit
Two nearly identical columns can support large, opposite least-squares coefficients, such as +40 and −38. Their combined prediction may look reasonable, but small changes in the data can change the coefficients sharply. Ridge makes those large values costly and tends to share predictive weight across the correlated columns.
For centered targets and standardized features, the matrix solution is:
A positive penalty makes the matrix invertible. Ridge therefore has unique slope coefficients even with perfect collinearity or more features than rows. This stability does not turn a coefficient into an unbiased effect estimate; ordinary least-squares standard errors and p-values do not apply unchanged.
Make feature units comparable
A floor-area coefficient of 2.5 per square meter becomes 0.00025 per square centimeter. Predictions can stay identical, but the coefficient square becomes vastly smaller. Without scaling, ridge would treat the two encodings differently simply because of their units.
Standardize using training means and standard deviations. A fitted slope then describes the predicted change for a one-standard-deviation increase in that feature, holding the other inputs fixed.
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
ridge = make_pipeline(StandardScaler(), Ridge(alpha=10))
ridge.fit(X_train, y_train)
Ridge minimizes RSS plus alpha times the squared weights. Its data term is a sum, so adding more rows changes the relative strength of the same alpha. Re-tune the penalty when the dataset or feature representation changes.
Key Takeaways
Ridgeadds the squared slope coefficients to RSS, weighted by the penalty strength.- A positive ridge penalty gives unique coefficients even with collinear inputs.
Ridgegenerally keeps all features while stabilizing their weights.- Standardization prevents arbitrary measurement units from deciding the penalty.
- Interpret ridge coefficients as predictive weights, not unbiased effects.
2.2 Select features with the lasso
The lasso adds an L1 penalty, the sum of absolute slope coefficients. It both shrinks coefficients and can set some exactly to zero, producing a sparse model that needs only a subset of the inputs.
Compare the two penalties
In textbook RSS notation, the lasso minimizes:
The intercept is unpenalized. The equivalent budget is . For weights , the L1 size is , while the squared L2 size is .
| Property | Lasso, L1 | Ridge, L2 |
|---|---|---|
| Penalty shape for two coefficients | Diamond | Circle |
| Behavior near zero | Constant pull toward zero | Pull weakens near zero |
| Feature selection | Can create exact zeros | Generally keeps nonzero weights |
| Correlated inputs | Often retains one representative | Often shares their effect |
The diamond has corners on the axes, where a coefficient is zero. RSS contours often first touch the budget at a corner. The circle is smooth, so its point of contact rarely lies exactly on an axis. This explains why L1 creates zeros more readily.
See soft thresholding in a special case
When the feature matrix is the identity and there is no intercept, the coefficients can be solved independently. Under the RSS objective above, lasso subtracts from a positive least-squares coefficient, adds it to a negative one, and sets the result to zero if the original magnitude is no larger than .
For least-squares estimates and , the threshold is 1. The lasso returns . Ridge instead divides each original coefficient by , giving approximately . The simple threshold formula belongs to this special design; correlated columns require a joint fit.
Interpret a selected set carefully
When two inputs carry nearly the same signal, the lasso may retain one and drop the other. A different fold may reverse that choice. A dropped feature can still be related to the outcome through a retained substitute, and predictive selection establishes no causal relationship.
A stronger penalty generally gives a shorter list, but the list need not shrink in a nested sequence. With correlated features, a coefficient can reach zero and later re-enter along the penalty path. For a unique lasso solution with more columns than rows, at most the number of rows can have nonzero coefficients; under nonuniqueness, some solutions can contain more.
Fit with software's objective
Lasso minimizes:
The average squared-error term makes alpha numerically different from ridge's sum-based strength. Fit standardized features, inspect coef_ for zeros, and tune alpha by cross-validation. The general problem is solved iteratively, commonly by coordinate descent. If convergence fails, check scaling and allow more iterations with max_iter.
Lasso is a useful candidate when only a few inputs have substantial predictive value or when collecting fewer inputs matters. Ridge may predict better when many small effects contribute. Compare them on the same validation splits.
Key Takeaways
Lassouses absolute coefficient size and can create exact zeros.- Soft thresholding has a simple formula for an identity feature matrix without an intercept.
- Correlated inputs can make the selected list unstable.
- A zero coefficient is a predictive fitting result, not a causal finding.
Lassoand ridge use different numeric scales for alpha in scikit-learn.- Compare prediction error and the cost of collecting retained features.
2.3 Mix L1 and L2 and control a classifier
Elastic net combines lasso's exact zeros with ridge's stabilization. It is useful when a sparse model is desirable but many candidate features form correlated groups.
Separate strength from mixture
In scikit-learn, elastic net minimizes:
alpha sets the overall strength. l1_ratio, represented by , sets the mixture. A value of 1 gives lasso; a value of 0 gives a pure L2 penalty, for which Ridge is the usual fitting choice. Because the objectives use different normalization, the same numeric alpha does not equate elastic net's pure L2 case with Ridge(alpha=...).
For weights , alpha=0.1, and l1_ratio=0.5, the absolute weights sum to 7 and the squared weights sum to 25. The L1 contribution is . The L2 contribution is . The total penalty is .
The L2 part encourages correlated features to share weight, called the grouping effect. L1 still allows irrelevant coefficients to become zero. Elastic net can retain more features than training rows, and a positive L2 component stabilizes the solution. Both the strength and mixture need tuning; a mixture is not an automatic improvement over either endpoint.
Regularize logistic regression
Logistic regression uses log loss, but its slopes can be regularized in the same way. In current scikit-learn, LogisticRegression defaults to L2 regularization with C=1.0.
| Setting | Penalty effect |
|---|---|
Smaller C | Stronger regularization |
Larger C | Weaker regularization |
C=np.inf | No regularization |
l1_ratio=0 | L2 |
l1_ratio=1 | L1 |
0 < l1_ratio < 1 | Elastic net |
With very strong regularization, slopes approach zero. With an unpenalized intercept, predicted probabilities approach the training share of the positive class. A constant probability does not have to be 0.5; the intercept preserves the class imbalance.
Match the solver to the penalty
L1 and elastic net need a compatible solver. saga supports both; lbfgs, the default solver, supports L2. The current penalty choice uses l1_ratio; older code may use the deprecated penalty parameter.
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
classifier = make_pipeline(
StandardScaler(),
LogisticRegression(solver="saga", l1_ratio=0.5,
C=0.2, max_iter=5000, random_state=7),
)
The scaler gives numeric features comparable units. C controls shrinkage, and l1_ratio controls the kind of shrinkage. Raising C while intending to fight overfitting reverses the intended change: it weakens the penalty.
Key Takeaways
- Elastic net tunes overall strength and the L1/L2 mixture separately.
- The L2 component helps stabilize correlated groups while L1 can retain sparsity.
LogisticRegressionapplies L2 regularization by default.- Smaller C strengthens the logistic penalty.
- Use a solver compatible with the selected penalty.
2.4 Choose a penalty on held-out folds
A penalty strength is a hyperparameter: it is chosen outside the coefficient-fitting step. Training error rewards flexibility, so use held-out predictions to decide how much shrinkage helps.
Search across orders of magnitude
Try a logarithmic grid such as . Equal multiplicative steps explore a much wider range of behavior than equal additive steps. np.logspace(-3, 3, 7) creates this grid. If the best value is at an edge, extend the range and repeat the training-set search.
First set aside the test data. For each candidate, run cross-validation on the remaining training data. Each fold must refit the scaler and model using only its training portion, then score its validation portion. Average the fold errors to compare candidates.
Choose minimum error or a simpler close competitor
Suppose ridge gives these cross-validated MSE values:
| alpha | Mean MSE | Standard error |
|---|---|---|
| 0.01 | 24.0 | 1.1 |
| 0.1 | 22.8 | 1.0 |
| 1 | 22.1 | 1.0 |
| 10 | 22.9 | 1.1 |
| 100 | 26.4 | 1.3 |
The minimum-error rule chooses alpha=1. The one-standard-error rule starts at the minimum and adds its standard error: . Values 0.1, 1, and 10 fall within that threshold. Choose the simplest of those candidates, here the strongest penalty, alpha=10. The rule uses the standard error at the minimum, not a different allowance for each row.
Read coefficient paths
A coefficient path plots each fitted coefficient against log penalty strength. Ridge paths approach zero smoothly. Lasso paths can reach zero, showing when a feature drops out. Read the path alongside validation error: a smaller feature list is useful only if its predictive cost is acceptable. Correlated features may leave and re-enter, so the active sets need not be nested.
Cross-validate the complete fitting procedure
import numpy as np
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
pipe = make_pipeline(StandardScaler(), Ridge())
search = GridSearchCV(
pipe, {"ridge__alpha": np.logspace(-3, 3, 7)},
cv=5, scoring="neg_mean_squared_error",
)
search.fit(X_train, y_train)
GridSearchCV fits a fresh scaler inside each fold. By contrast, placing RidgeCV, LassoCV, ElasticNetCV, or LogisticRegressionCV after a scaler lets those estimators' internal folds reuse scaling learned from all rows passed to the scaler. Their built-in tuning is convenient, but that placement does not isolate preprocessing within the internal folds. RidgeCV uses efficient leave-one-out validation by default; path-based estimators can make large searches faster.
After choosing the strength, refit the pipeline on all training rows. GridSearchCV does this automatically by default. Evaluate the finished pipeline once on the untouched test set. The best inner cross-validation score is optimistic because it won a search; an outer loop of nested cross-validation can instead estimate the performance of the whole tuning procedure.
Key Takeaways
- Search penalty strengths across orders of magnitude.
- Refit every learned preprocessing step inside each validation fold.
- The one-standard-error rule chooses the simplest model within one standard error of the minimum.
- Coefficient paths show how shrinkage changes the active features.
- Refit the selected pipeline on all training rows before final testing.
- Use an untouched test set or outer cross-validation to assess the tuned procedure.
3Select the features a model uses
Choosing inputs changes both what a model can learn and what data must be collected to run it. A smaller feature set can reduce variance and make predictions easier to explain, but searching for that set can also overfit. Subset searches, fast filters, and embedded methods make different compromises. Their performance must be measured on rows that did not influence the selection, just as with any other fitted part of a model.
3.1 Compare searches over feature subsets
Feature selection keeps some inputs and discards others. It can reduce measurement cost, simplify interpretation, and lower variance. Three families differ in how they make the choice.
| Family | How it selects | Example |
|---|---|---|
| Filter | Scores inputs before the final model | Univariate F-test |
| Wrapper | Fits models on candidate subsets | Forward selection |
| Embedded | Selects while fitting the model | Lasso |
Count the search before running it
Best subset selection fits every subset of features, including the empty subset: models. Ten features require 1,024 fits; twenty require 1,048,576. It finds the best training subset at each size, but choosing among the sizes still needs a fair comparison.
Forward stepwise selection starts empty and adds the best single remaining feature at each step. The full path requires fits: 56 for ten features and 211 for twenty. Backward stepwise selection starts with all features and removes one at a time. Ordinary least-squares backward selection needs more rows than features to begin with a uniquely estimable full model; forward search can begin when there are more features than rows.
Stepwise search is greedy. The best single feature may not belong to the best pair, but forward selection keeps its first choice. Its nested sequence is cheaper to search and can miss the globally best subset.
Charge for model size
Adding a feature cannot worsen the best training RSS or lower ordinary training R-squared. Those quantities alone therefore favor large models. Cross-validation compares held-out predictions; adjusted criteria charge for extra fitted parameters.
For rows and features:
With 50 rows, a five-feature model with has adjusted R-squared about 0.777. A twelve-feature model with scores about 0.775 after adjustment. The extra training fit does not cover the added complexity.
Mallows' criterion is:
where counts coefficients including the intercept and is an error-variance estimate, usually from the full model. Lower is better; a model with little bias has a value near its coefficient count. If the full twelve-feature model has RSS 148, its variance estimate is and its Cp is . The five-feature model has RSS about 174.1, giving Cp about 5.5.
AIC charges 2 per parameter; BIC charges . For , BIC's complexity charge is larger. AIC and Cp give the same ranking for Gaussian least-squares comparisons with a shared fixed variance estimate; estimating variance separately in each model need not give exactly the same ranking.
Use a selection estimator
SequentialFeatureSelector evaluates additions or removals with cross-validation. RFE repeatedly removes features with the smallest fitted coefficient magnitudes or importances; RFECV also tunes the retained count. Standardize before coefficient-based ranking. To estimate the full search's performance, place selection inside the outer validation procedure: the selected model's training R-squared and ordinary p-values ignore the earlier search.
Key Takeaways
- Best subset search grows exponentially; stepwise search is cheaper but greedy.
- Training RSS and R-squared cannot choose feature count fairly.
- Adjusted R-squared, Cp, AIC, and BIC include complexity charges.
- Count the intercept in Cp and use a suitable error-variance estimate.
- Evaluate selection on data the search never saw.
3.2 Keep filters and embedded selection inside validation
A quick feature score can remove thousands of weak inputs before a model is fitted. The score still learns from data. If selection uses held-out labels, those labels have already influenced the model that will be evaluated.
Use a filter for the question it answers
VarianceThreshold() removes constant training columns by default. A positive threshold also removes low-variance columns, but its meaning depends on units: variance measured in meters differs from variance measured in centimeters.
Univariate filters examine each feature's relation to the target on its own. f_regression scores linear association with a regression target; f_classif compares class means. Mutual information can detect nonlinear dependence. SelectKBest retains a chosen count, and SelectPercentile retains a chosen percentage.
A strong individual score does not ensure a useful combination. Two duplicate measurements can both rank highly and add redundant information. A feature can also be useful only through an interaction. In a balanced XOR example, two binary inputs predict 1 exactly when they differ. Each input alone gives no information about the target, yet the pair determines it.
Select through a fitted model
Embedded selection uses coefficients or feature importances learned during fitting. SelectFromModel can select from a lasso or L1 logistic model, or apply a threshold to tree-ensemble importances. Coefficient magnitudes need comparable feature scales. A lasso-selected list can change between folds when inputs are correlated, so count selection frequency across folds if a stable list matters.
A feature discarded in one fit may have a nearly equivalent substitute. Read the retained list as one predictive solution, not a definitive list of causes.
Prevent selection leakage
The scikit-learn leakage example uses 200 rows, 10,000 random features, and random binary targets. Selecting the best 25 features on the whole dataset before splitting yields accuracy around 0.76 despite a chance level of 0.5. The selector has searched for accidental relationships involving the test labels.
Fit the selector within each training fold instead:
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
pipe = make_pipeline(
StandardScaler(),
SelectKBest(f_classif, k=20),
LogisticRegression(),
)
Cross-validating pipe refits scaling, scores, and model in each fold. Tune the count with selectkbest__k, using a search over the whole pipeline. Selecting once before cross-validation exposes every validation fold to the search, even if the final classifier is refitted correctly.
Check whether an input exists at prediction time
Remove leaky columns before comparing selectors. A hospital-admission model cannot use the eventual length of a hospital stay: that value is unknown at admission prediction time. No validation score makes an unavailable input usable.
For thousands of columns, a fast filter can be a useful first pass. Wrapper searches suit smaller candidate sets. Lasso and elastic net combine selection with regularization for linear models. Compare these choices with regularization alone; a separate selector is useful only if its predictive or practical benefit justifies it.
Key Takeaways
- Univariate filters are fast but can retain redundancy and miss interactions.
- Embedded methods select through fitted coefficients or importances.
- Fit target-based selection inside every validation fold.
- Remove information unavailable at prediction time before any selection.
- Selection frequency across folds helps reveal unstable choices.
- Compare a separate selector with regularization alone.
4Engineer, encode and scale features
Raw columns rarely give a model exactly the representation it needs. Categories need numeric encodings, measurements may need new combinations, and numeric ranges can distort distances or penalties. Each change has a purpose: preserve a meaningful order, express a relationship, or make inputs comparable. The model determines which changes help, and validation checks that benefit while keeping learned categories, thresholds, and scaling statistics inside training folds.
4.1 Represent categories without inventing an order
A nominal category has no natural order, such as a payment method. An ordinal category has an order, such as small, medium, and large. Numeric encoding must preserve that distinction.
Give unordered values separate columns
One-hot encoding creates a 0/1 column per category. With columns red, green, and blue, the value "green" becomes . Unlike arbitrary integer codes, this gives a linear model no false rank or equal-spacing assumption. OneHotEncoder learns categories during fitting and returns a memory-saving sparse matrix by default.
With an intercept, all one-hot columns for one variable add to the intercept column. This dummy-variable trap makes ordinary unregularized least-squares coefficients nonunique. Dropping one of four city columns leaves three; each remaining coefficient is a difference from the omitted baseline.
A positive L2 penalty gives unique coefficients despite that collinearity, so ridge can keep all category columns. Trees do not solve a coefficient system and also do not need a dropped baseline. Keeping all categories avoids making penalization depend on an arbitrary baseline. L1 alone does not guarantee unique coefficients under perfect collinearity.
State a real order explicitly
from sklearn.preprocessing import OrdinalEncoder
sizes = OrdinalEncoder(categories=[["small", "medium", "large"]])
This maps the sizes to 0, 1, and 2 in their meaningful order. Default alphabetical sorting would place "large" first. A linear model also treats adjacent integer codes as equally spaced effects, so even a genuine order needs a suitable modeling choice. Use LabelEncoder for target labels, not input columns.
Plan for new and rare categories
OneHotEncoder raises an error for unknown categories by default. With handle_unknown="ignore", a category unseen in training becomes all zeros. handle_unknown="infrequent_if_exist" sends it to the infrequent-category column if one was created. min_frequency and max_categories can group rare categories.
A high-cardinality feature has many distinct values, such as thousands of product IDs. One-hot encoding may create many rarely used columns. Grouping rare values, encoding training frequencies, or using target encoding can make a smaller representation.
Keep target means from leaking
Target encoding replaces a category with a smoothed target mean:
Here is the category count and is the smoothing strength. The overall target mean pulls rare categories toward a more stable value. For overall rate 0.30, four category rows with rate 0.75, and smoothing 10, the encoded value is . With 400 rows at the same rate, it is .
Smoothing does not remove the need for cross fitting. TargetEncoder.fit_transform(X_train, y_train) encodes each training fold using means learned from other folds. New rows use transform, with statistics stored from training. Calling fit(X_train, y_train).transform(X_train) lacks that cross fitting: a row's own target can shape its input. Fit the encoder only on the training part of each outer validation fold.
Key Takeaways
- Choose one-hot encoding for nominal categories and explicit order for ordinal categories.
- Full one-hot columns plus an intercept create collinearity in unregularized linear regression.
- Plan how the encoder handles unseen and rare categories.
- Target encoding smooths category means toward the overall mean.
- Cross-fit training target encodings so each row excludes its own target.
- Learn categories and frequencies from training rows only.
4.2 Build features that express the relationship
A linear model is linear in its coefficients, not necessarily in the raw measurements. Feature engineering gives it useful inputs. Multiplying a plot's frontage by its depth creates area, a relationship that separate frontage and depth terms cannot represent directly.
Add powers and interactions deliberately
For inputs and , degree-two polynomial expansion produces . The squares allow curvature; the product allows the inputs to act jointly.
With inputs and degree , the count including the constant is . Three inputs at degree two give ten columns, or nine without the constant. Ten inputs at degree three give 286. This growth raises both computation and overfitting risk, so tune degree and regularization together.
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import Ridge
curve = make_pipeline(
PolynomialFeatures(degree=2, include_bias=False),
StandardScaler(),
Ridge(alpha=1),
)
Scale after expansion: if an input is 10, its square is 100 and its cube is 1,000. Scaling only the original input does not guarantee comparable scales for all generated terms. include_bias=False omits a constant column when the model already fits an intercept.
An interaction such as temperature times insulation lets one input's effect depend on another. interaction_only=True creates products of distinct inputs without pure powers.
Match the feature to the information
| Construction | Useful pattern | Decision to make |
|---|---|---|
| Ratio | Debt relative to income | Handle a zero denominator |
| Difference | Days since last purchase | Define the prediction date |
| Binning | Step-shaped effects | Learn bin edges on training rows |
| Splines | Smooth changes across ranges | Tune the flexibility |
A ratio with a zero denominator can be marked missing and imputed under a fixed rule. Binning loses differences inside each interval; a spline represents smoother variation with piecewise polynomials. KBinsDiscretizer and SplineTransformer learn their settings during fitting.
Preserve the cycle in a date or time
Month, weekday, hour, and elapsed account age can expose different patterns. Raw hour codes put 23 far from 0 even though those hours are adjacent. Encode hour as:
Hour 23 is approximately and midnight is , about 0.26 apart. Noon is , at distance 2 from midnight. Both coordinates are needed to locate an hour around the circle.
Respect the prediction boundary
An average customer purchase computed with future months leaks future information. Build historical aggregates using only records available at the prediction date. Put custom fixed operations in a FunctionTransformer and learned operations in fitted transformers so training and prediction use the same construction.
Linear and distance-based models often gain most from engineered inputs. Trees already learn thresholds and some interactions, but ratios or time parts can still help. Keep additions when validation or a practical collection benefit supports them.
Key Takeaways
- A linear model can fit nonlinear raw-input relationships through engineered features.
- Polynomial expansion grows quickly, so tune degree with regularization.
- Scale generated polynomial columns after expansion.
- Interactions let one input change another input's effect.
- Use sine and cosine together for cyclical time.
- Build every feature from information available at the prediction date.
4.3 Choose scales and transformations
Scaling changes the numerical size of a feature. A transformation can also change its shape. Distance-based methods, gradient descent, and penalized models depend on these choices; a large numeric range can dominate distances or make a coefficient cheap to penalize.
Compare column scalers
| Method | Calculation | Main use |
|---|---|---|
| Standardization | Subtract training mean, divide by training SD | Comparable scales for linear models |
| Min-max | Subtract training minimum, divide by training range | A chosen training interval |
| Robust | Subtract training median, divide by IQR | Less sensitivity to extreme values |
| Max-absolute | Divide by largest absolute training value | Sparse columns that should keep zeros |
For training values 10, 20, 30, 40, and 50, the mean is 30. StandardScaler uses population variance, dividing squared deviations by 5, so the standard deviation is . The value 50 becomes .
Min-max scaling uses . The training maximum becomes 1, but a new value 60 becomes 1.25. The training range defines the mapping; it does not confine future values to that range.
For robust scaling, the median is 30 and the quartiles are 20 and 40. The IQR is 20, so 60 becomes . This makes the scaling statistics less sensitive to outliers; it does not remove the outliers.
Tree models split at thresholds, so ordinary rescaling of a feature does not change the possible divisions of the rows. One-hot 0/1 columns are often left unchanged. Normalizer is different from these scalers: it rescales each row to unit length, not each column by its training statistics.
Change a skewed distribution's shape
A log transform compresses large positive values. Values 20,000, 40,000, and 80,000 have base-ten logs about 4.301, 4.602, and 4.903: doubling becomes an equal additive step. Ordinary logarithms require positive values. np.log1p computes and handles nonnegative inputs including zero.
If the target is logged, predictions must be mapped back to its original scale. TransformedTargetRegressor pairs a target transformation with an inverse transformation for prediction.
Box-Cox estimates a power transformation for strictly positive values. Yeo-Johnson also handles zeros and negative values; it is the default in PowerTransformer, which standardizes its output by default. QuantileTransformer maps empirical ranks to a uniform or normal distribution. It controls extreme values but can alter the distances between observations.
Standardizing a skewed feature leaves it skewed: changing mean and standard deviation does not make the distribution normal. Choose a shape transformation because the model benefits, not because every input must look Gaussian.
Store the training mapping
Fit means, standard deviations, ranges, quartiles, and power parameters on training rows only. Use those same values for validation and future rows. Refitting a scaler on test data changes the feature coordinates that the trained model expects. Cross-validation therefore refits the transformer within each training fold, then applies it unchanged to that fold's validation rows.
Key Takeaways
- Scaling matters for distances, optimization, and coefficient penalties.
- Standardization changes location and scale, not distribution shape.
- New min-max-scaled values can fall outside the training interval.
- Robust scaling uses the median and IQR; max-absolute scaling preserves zeros.
- Box-Cox needs positive values; Yeo-Johnson also supports zero and negative values.
- Apply stored training statistics to held-out and future rows.
5Build reproducible preprocessing pipelines
A model in use receives raw rows, including missing measurements and categories it may not have seen before. Its preprocessing must reproduce the decisions made during training. Pipelines join those steps with the estimator, and column transformers route different columns through different preparations. Tuning that complete object keeps validation honest and produces one fitted procedure that can be inspected, saved, and applied to future data.
5.1 Fill missing inputs without using held-out data
Missing inputs can appear as NaN, None, empty cells, or placeholder codes. A value such as −999 may mean "not measured" instead of an actual measurement. Convert such codes to missing values or configure the imputer to recognize them before fitting.
Ask why the data is missing
Start with the missing fraction per column, for example df.isna().mean(). Then consider the process that produced the gaps.
| Mechanism | What missingness depends on | Example |
|---|---|---|
| MCAR | Neither observed nor missing values | Random sensor dropouts |
| MAR | Observed information | Recorded age predicts a skipped answer |
| MNAR | The missing value itself | Higher incomes are less often reported |
These mechanisms affect how representative the observed rows are. Simple imputation can bias relationships under MAR and MNAR. Missingness can itself carry predictive information, so the reason for a gap matters as well as its frequency.
Compare deletion with imputation
Deleting incomplete rows can discard much more data than expected. If ten columns each independently miss 5% of their values, the complete-row share is . About 40% of rows disappear. Complete-case deletion can also change the population represented when missingness is not completely random, and it does not supply a prediction strategy for incomplete future rows.
Simple imputation fills a column using a training mean, median, most frequent category, or fixed value. For observed values 4, 6, 8, and 100, the mean is 29.5 and the median is 7. The median resists the influence of the extreme value. Categorical inputs can use the most frequent category or a separate "missing" category.
A missing indicator adds a 0/1 column marking a gap. SimpleImputer(add_indicator=True) adds indicators for features with missing values during fitting. Two rows with the same filled value can then still differ in whether that value was observed or imputed.
Use other features to estimate a gap
KNNImputer borrows values from similar training rows, using distances over observed coordinates. Scale the columns first so large numeric ranges do not dominate the neighbors; keep the scaler and imputer inside each fold.
IterativeImputer predicts a missing feature from the other features, cycling through incomplete columns for several rounds. It is experimental and requires its enabling import. Both approaches cost more than a simple fill and should earn that cost through validation.
Some estimators, including histogram gradient boosting and recent scikit-learn tree and random-forest implementations, accept missing values directly. Linear models, k-nearest neighbors, and support vector machines need a complete numeric representation.
Learn replacement values only during fitting
An imputer fitted on the whole dataset lets held-out rows affect its replacement values. Fit within the training split or each training fold, then apply the stored mapping to validation and future data. Compare mean, median, model-based imputation, and indicators under the same validation procedure.
Mean imputation reduces a column's spread and can weaken its correlations; a completed table is not a recovery of the original observations. Rows without a target are excluded from supervised training. Filling a missing target with a guess would train the model against an invented outcome.
Key Takeaways
- Identify placeholder codes before measuring or imputing missingness.
- MCAR, MAR, and MNAR describe different missingness processes.
- Deletion can remove many rows and change the represented population.
- Choose an imputation method by validation, and consider a missing indicator.
- Scale before KNN imputation and learn all replacements within training folds.
- Exclude rows with missing targets from supervised training.
5.2 Route columns through one fitted pipeline
A pipeline chains transformations and a model into one fitted object. During fit, each transformer learns from the training data and passes its output to the next step. During predict, the stored transformations run in the same order before the final model predicts.
Distinguish learning from applying
fit learns quantities such as medians, category lists, and coefficients. transform applies a learned mapping. fit_transform combines those actions on training data. Validation and future data use stored transformations; they do not fit fresh means or categories.
ColumnTransformer prepares different groups of columns in parallel and joins the results. Numeric columns may need median imputation and scaling. Categorical columns may need most-frequent imputation and one-hot encoding. Unlisted columns are dropped by default; remainder="passthrough" retains them unchanged.
Build a complete mixed-column model
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import Ridge
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
num = make_pipeline(
SimpleImputer(strategy="median"), StandardScaler()
)
cat = make_pipeline(
SimpleImputer(strategy="most_frequent"),
OneHotEncoder(handle_unknown="ignore"),
)
preprocess = ColumnTransformer([
("num", num, ["area_m2", "rooms", "age_years"]),
("cat", cat, ["neighborhood", "heating_type"]),
])
model = Pipeline([
("preprocess", preprocess), ("ridge", Ridge(alpha=1.0))
])
model.fit(X_train, y_train)
The column lists define the input contract. All medians, scaling statistics, and categories come from X_train. On a new row, a missing area receives the stored training median; an unknown heating type follows the encoder's unknown-category policy.
Order steps by what they need
A simple imputer can precede scaling because it fills each column independently. KNN imputation uses distances, so a scaler should precede it. Suitable scalers ignore missing values while fitting and preserve them for the imputer. Both are fitted in each training fold.
Polynomial expansion comes before scaling so the new powers and products also get scaled. Encoding and scaling precede coefficient-based selection, and the predictor comes last. Merely putting an estimator in a pipeline does not repair data that was already transformed using held-out statistics.
Validate and inspect the joined object
cross_val_score(model, X_train, y_train, cv=5) fits a fresh copy of the entire chain in each fold. Preprocessing outside that call would expose fold statistics before evaluation.
Inspect coefficients through model.named_steps["ridge"].coef_. Retrieve matching output names with model[:-1].get_feature_names_out(), which can return names such as num__area_m2. Matching names to coefficient positions prevents interpreting an encoded column as an original input.
Transformers can return DataFrames with set_output(transform="pandas"). One-hot output must then be dense, using sparse_output=False, because pandas output does not accept that sparse matrix. make_pipeline assigns lowercase class names such as standardscaler; an explicit Pipeline lets you choose step names used in tuning paths.
Key Takeaways
- Fit learns parameters; transform applies stored parameters.
ColumnTransformerapplies different preparations to named column groups.- Order transformations so each step receives the representation it needs.
- Cross-validate the whole pipeline to refit preprocessing in each fold.
- Inspect transformed feature names alongside model coefficients.
5.3 Tune, save, and reuse the complete procedure
Preprocessing choices are part of the model search. An imputation strategy, polynomial degree, selector count, and penalty strength can all change predictive performance. Tune them together on training data so every candidate is judged under the same information boundary.
Address settings by their step paths
For the mixed-column pipeline, parameter names join nested steps with double underscores:
from sklearn.model_selection import GridSearchCV
param_grid = {
"ridge__alpha": [0.1, 1, 10, 100],
"preprocess__num__simpleimputer__strategy": [
"mean", "median", "most_frequent"
],
}
search = GridSearchCV(
model, param_grid, cv=5,
scoring="neg_mean_squared_error",
)
search.fit(X_train, y_train)
Four strengths and three imputation strategies create twelve combinations. Five folds require sixty candidate fits, followed by one refit of the winning pipeline on all training rows when refit=True, the default. A step can also be replaced or set to "passthrough" to compare a procedure with and without it.
Interpret search results on the right scale
scikit-learn maximizes scores. Negative MSE reverses an error metric so larger remains better. A best_score_ of −22.1 therefore means MSE 22.1. best_params_ gives the chosen settings, cv_results_ gives the comparison, and best_estimator_ is the fitted winning pipeline.
The winning validation score benefits from having won the search. Evaluate the selected procedure on a test set held out before tuning, or use nested cross-validation with an inner search and an outer evaluation loop. For classification, stratify an ordinary random split to preserve class proportions. Split design must still match the prediction task.
After the final test, revising features or settings in response to its score turns that set into validation data. Report the result for the procedure that was fixed before the test.
Make the run reproducible
Record the exact data snapshot, code, and library versions. Set random_state on shuffled splitters and randomized estimators. For example, KFold(shuffle=True, random_state=0) produces a reproducible split sequence. Put preprocessing and fitting in a script so rerunning them does not depend on notebook execution order.
Save the fitted pipeline, including preprocessing:
import joblib
joblib.dump(search.best_estimator_, "model.joblib")
loaded = joblib.load("model.joblib")
predictions = loaded.predict(X_new)
Load pickle or joblib artifacts only from trusted sources, because loading can execute code. skops.io offers a safer persistence option. Keep library versions pinned; loading across scikit-learn versions is unsupported.
Preserve the prediction contract
New rows need the same input column names and compatible types. The saved imputer supplies stored fills, the encoder supplies stored category columns, and the scaler supplies stored coordinates. Predict directly with the loaded object. Refitting it on each arriving batch changes its learned mappings and requires retraining the predictor to match.
Key Takeaways
- Tune preprocessing and estimator settings with nested step__parameter paths.
- A grid of twelve candidates with five folds needs sixty candidate fits plus the final refit.
- Convert a negative error score back to the positive error when reporting it.
- Use a held-out test or outer folds to evaluate the selected procedure.
- Record data, code, versions, and random seeds.
- Save the fitted pipeline and predict with its stored transformations.
Regularization and Feature Engineering examples
1Diagnose a model before changing it
10 steps
- 1IntroductionStart with the prediction task
A training score answers how well a model fits familiar rows. You also need predictions for rows excluded from fitting. Compare both errors with a simple baseline before deciding whether to simplify or expand the model, the choice between overfitting and underfitting, which need opposite fixes.
We will follow a regression example, then see how a coefficient penalty changes what the fitting procedure rewards.
- 2ExampleRead three candidate fits
Suppose a mean-prediction baseline has RMSE 5.0. On the same noisy input, degree-one regression gives training/validation RMSE 4.1/4.3; degree four gives 1.9/2.1; degree fifteen gives 0.4/7.8.
The training error falls with degree, but the validation error does not. Degree four captures useful structure without the severe transfer failure of degree fifteen.
- 3ExplanationConfirm what high errors mean
The degree-one model has high, close errors. That pattern suggests underfitting, and the degree-four improvement on the same input confirms it: a more flexible relationship was learnable.
If several flexible alternatives had failed too, weak inputs would be another explanation. The size of the error gap alone cannot tell you whether the available measurements contain a useful signal.
- 4ChallengeChoose evidence for the diagnosis
A model scores 69% on training and 68% on validation, while the majority baseline scores 67%. What extra comparison would support an underfitting diagnosis?
---reveal---
A more flexible model on the same inputs should improve validation performance substantially. Close scores show a small gap, but the near-baseline level could also come from inputs with little predictive information.
- 5ConnectionUse learning curves for the next decision
A learning curve adds rows while keeping the fitting approach fixed. If training and validation errors level off high and close, more rows alone are unlikely to solve the problem. If a large gap narrows as rows are added, extra data can reduce variance.
This connects the diagnosis to an action: add flexibility for confirmed underfitting, or consider more data and a less variable fit for overfitting.
- 6ExplanationAdd a cost for coefficient size
An L2 penalty makes large slopes expensive. For rows, add to the averaged squared-error fit term. The intercept is excluded so the overall prediction level can remain appropriate.
The optimizer can now prefer a modest increase in training error if it buys a substantial reduction in coefficient size. Validation decides whether that trade improves predictions.
- 7ExampleCompute the two cost terms
Use four errors: 1, −1, 2, and 0. Their squares total 6, so the fit term is . For weights (3, −2), the squared sizes total 13.
At strength 1, the penalty is . Adding the two terms gives cost 2.375. This number evaluates this candidate weight vector; finding the fitted vector still requires minimizing the objective.
- 8ChallengeStrengthen or weaken the penalty
The slopes of a heavily penalized model are almost zero. Both errors are poor, and reducing the penalty improves validation predictions. What should the next penalty search explore?
---reveal---
Explore weaker penalties. The model was too constrained, and the validation improvement supports giving its slopes more freedom. In ridge this means smaller alpha; in logistic regression it means larger C.
- 9ChallengeConnect the score pattern to a remedy
A high-degree model predicts training rows almost perfectly but performs worse than a constant baseline on validation. A colleague recommends raising degree again. What change is better supported?
---reveal---
Try reducing degree or strengthening regularization and compare validation errors. The current gap signals overfitting, so extra flexibility moves in the wrong direction. More comparable training rows can also help reduce variance.
- 10RecapChoose the next experiment from evidence
Use the error level and the gap together. A flexible alternative can confirm underfitting; a large failure on held-out rows supports overfitting. Learning curves add evidence about the value of more data.
A penalty gives another control on flexibility, but a nearly constant model can also underfit. Choose its strength through held-out predictions, with the direction of the software parameter kept clear.
2Follow coefficients from shrinkage to selection
17 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionChoose what the penalty should achieve
- 2ExplanationRidge charges for squared slopes
- 3ExampleCalculate a no-intercept slope
- 4ChallengePredict a unit change
- 5ExplanationLasso can reach exactly zero
- 6ExampleFind the soft threshold
- 7ExampleApply the threshold to each coefficient
- 8ChallengeInterpret a disappearing feature
- 9ConnectionCombine sparsity with shared weights
- 10ExampleCompute a mixed penalty
- 11ChallengeMove logistic strength in the right direction
- 12TipSearch strengths with the scaler inside
- 13ExampleFind the minimum validation error
- 14ExampleChoose a close simpler candidate
- 15ChallengeCombine the selection and validation decisions
- 16Key InsightSeparate choosing from assessing
- 17RecapRead both the model and its evidence
3Select features without selecting the validation result
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTreat the feature list as a learned choice
- 2ExampleCount all subsets
- 3ExampleBuild a forward path
- 4Key InsightWhy training fit keeps rewarding inputs
- 5ExampleCount the intercept in Cp
- 6ChallengeJudge a higher training score
- 7ExplanationChoose a fast filter deliberately
- 8ExampleSee the interaction a filter misses
- 9ChallengeRepair target-based selection
- 10ChallengeCombine timing with stable selection
- 11RecapEvaluate the search as part of the model
4Turn raw columns into useful model inputs
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionGive the model a useful representation
- 2ExplanationDistinguish category order
- 3ExampleBuild indicators and choose a baseline
- 4ChallengePrepare for a new category
- 5ExampleSmooth a rare target mean
- 6TipKeep a row out of its own target encoding
- 7ExplanationMake a linear model represent a curve
- 8ExampleCount and scale the new columns
- 9ExamplePut a clock hour on a circle
- 10ChallengeMake an aggregate available at prediction time
- 11ExampleStandardize from stored statistics
- 12ExampleRead values beyond the training range
- 13ConnectionChange shape only when it helps
- 14ChallengeChoose the right preprocessing claim
- 15ChallengeCombine construction and scaling
- 16RecapMatch each change to a purpose
5Build a pipeline that survives new data
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFollow a raw row through the model
- 2ExplanationInspect the gaps before filling them
- 3ExampleCompare a mean and a median
- 4ChallengeExplain the hidden cost of deletion
- 5TipChoose the order for distance-based filling
- 6ExplanationRoute numeric and category inputs
- 7ExampleAssemble the two branches
- 8ExampleTransform one incomplete future row
- 9ChallengeFind the validation boundary
- 10ExampleTune a nested preprocessing choice
- 11Key InsightRead the winning score correctly
- 12ChallengeKeep evaluation independent
- 13TipSave the fitted preparation with the predictor
- 14ChallengeRepair a changing prediction
- 15RecapKeep one procedure from fitting to use
Regularization and Feature Engineering practice questions
Set 1: Read model fit and compare penalties10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
l1_ratio 0.25. What is the total penalty under the scikit-learn elastic net objective?Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
Show answerHide answer
Set 2: Tune penalties and select useful inputs10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Ridge candidates have alpha values 0.2, 2, 20, and 200, with mean CV MSE 14.3, 13.8, 14.5, and 16.1. The standard error at the minimum is 0.9. What alpha does the one-standard-error rule choose?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
StandardScaler followed by LassoCV in a pipeline and calls fit on all training rows. She wants each internal validation fold excluded from scaling as well as coefficient fitting. What setup achieves that?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 3: Design encodings and numeric features10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
handle_unknown="ignore". How does it encode a fifth, previously unseen category?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
StandardScaler fitted on training data is applied to a right-skewed column. What happens to that column's distribution shape?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 4: Fit and reuse a complete pipeline10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
KNNImputer on numeric columns whose ranges differ greatly. Where should a missing-value-compatible scaler go?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
ColumnTransformer lists numeric and categorical columns but leaves an extra identifier column unlisted. With its default remainder setting, what happens to that identifier?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
best_score_ = −7.6. What MSE does this represent?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 5: Resolve combined modeling decisions10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
include_bias=False. A colleague also wants an hourly feature that preserves the daily cycle. What feature count and preparation give a suitable representation?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
refit=True each time. Excluding any later deployment fit, what fit count and score should be reported for the procedure?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Adjusted R-squared
Akaike information criterion
B
Backward stepwise selection
Bayesian information criterion
Best subset selection
Bias
Binning
Box-Cox transformation
C
Coefficient path
Collinearity
Column transformer
Complete-case deletion
Coordinate descent
Lasso fitting cycles through coefficients until the updates meet the solver's convergence requirements.Cross fitting
TargetEncoder.fit_transform makes a training row's encoded value without using its own outcome in the category mean.Cyclical encoding
D
Data leakage
Dummy-variable trap
E
Elastic net
Embedded selection
Lasso performs embedded selection because its fitted zero coefficients remove features during optimization.F
Feature engineering
Feature-name propagation
Filter selection
Fit
Forward stepwise selection
Frequency encoding
G
Generalization
Grid search
Grouping effect
H
High cardinality
Hyperparameter
I
Input contract
Interaction feature
Intercept
Inverse regularization strength
Iterative imputation
K
KNN imputation
L
L1 penalty
L2 penalty
Lasso
Learning curve
Log transformation
Logarithmic grid
M
Mallows' Cp
MAR
Max-absolute scaling
MCAR
Min-max scaling
Missing indicator
Mixing ratio
l1_ratio of 0.8 favors L1 while retaining an L2 component to stabilize correlated feature groups.MNAR
Model complexity
Model persistence
Mutual information
N
Negative error score
Nested cross-validation
Nominal variable
O
One-hot encoding
One-standard-error rule
Ordinal variable
Overfitting
P
Penalty strength
Pipeline
Polynomial feature
Q
Quantile transformation
R
Random state
Ratio feature
Recursive feature elimination
RFE needs comparable input scales so numeric units do not determine the elimination order.Refit
GridSearchCV refits the winning pipeline by default, making best_estimator_ ready for held-out prediction.Regularization
Reproducibility
Residual sum of squares
Ridge adds a complexity charge to RSS, so a smaller training RSS alone does not decide the fitted weights.Ridge regression
Ridge regression is a linear fitting method that adds a squared-coefficient penalty to the residual sum of squares.Ridge stabilizes a price model whose area and room-count measurements carry strongly overlapping signal.Robust scaling
Row normalization
Normalizer changes the magnitude of a row vector without estimating a separate mean for each input column.S
Selection stability
Shrinkage
Simple imputation
Soft thresholding
Solver
Sparse matrix
OneHotEncoder uses sparse output by default because each row activates only a small share of category columns.Sparse model
Spline
Standardization
T
Target encoding
Transform
U
Underfitting
Univariate score
V
Variance
W
Weight decay
Wrapper selection
Y
Yeo-Johnson transformation
PowerTransformer can compare a skewed signed measurement using Yeo-Johnson inside each training fold.About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.