Regularization and Feature Engineering

Learn to tell when a model is too simple or too flexible, and how to fix it. Shrink coefficients with ridge, lasso and elastic net, choose the penalty strength by cross-validation, and select features without fooling yourself. Then turn raw data into good features: encode categories, build new features, scale and transform numbers, and fill in missing values, all inside scikit-learn pipelines that are tuned, tested and reused without data leakage.

IntermediateLesson 5 of 9 in Machine Learning Course

What you will learn

  1. 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 underfitting
      Compare 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 penalty
      Choose a remedy for overfitting or underfitting, and explain how a regularization term in the cost function shrinks the weights, with λ setting the trade-off.
  2. 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 regression
      Write 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 lasso
      Write 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 classifiers
      Use 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-validation
      Search 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.
  3. 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 subsets
      Explain 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 leakage
      Apply variance and univariate filters and model-based selection, and keep selection inside cross-validation so the performance estimate stays honest.
  4. 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 variables
      Choose 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 ones
      Build 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 features
      Decide when scaling matters, apply standardization, min-max and robust scaling and log or power transforms, and learn every transformation from the training data only.
  5. 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 values
      Recognize 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 ColumnTransformer
      Combine 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 pipeline
      Tune 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.

Regularization and Feature Engineering study guide

5 chapters

1

Diagnose 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 degreeTraining RMSEValidation RMSEReading
14.14.3Too simple for this pattern
41.92.1Useful fit that transfers
150.47.8Fits 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:

bias2+variance+σ2.

The noise variance σ2 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 m rows and n features, an L2-regularized cost is:

J(𝐰,b)=12m∑i=1m(f𝐰,b(𝐱(i))−y(i))2+λ2m∑j=1nwj2.

The first term measures prediction error. The second adds the squared weights and multiplies that total by the nonnegative penalty strength λ. The intercept b is left out: it sets the overall prediction level, and penalizing it would pull predictions toward zero.

With four prediction errors 1,−1,2,0, the squared errors sum to 6. Dividing by 2m=8 gives a fit term of 0.75. For weights (3,−2) and λ=1, the squared weights sum to 13, so the penalty is 13/8=1.625. The total cost is 0.75+1.625=2.375. A candidate with slightly worse fit but much smaller weights can have a lower total cost.

Set the amount of shrinkage

With λ=0, 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.

DiagnosisUseful changes
OverfittingMore training rows, fewer features, a simpler model, or stronger regularization
UnderfittingBetter 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:

wj:=wj(1−αλm)−αm∑i(f𝐰,b(𝐱(i))−y(i))xj(i).

The extra factor shrinks the existing weight before the usual error-gradient contribution. With α=0.01, λ=10, and m=50, it is 1−0.01(10/50)=0.998. 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:

−1m∑i[y(i)log⁡f(i)+(1−y(i))log⁡(1−f(i))].

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

Shrink 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 p slope coefficients, ridge minimizes:

RSS+λ∑j=1pβj2.

The intercept β0 is unpenalized. An equivalent view is to minimize RSS while keeping ∑jβj2≤s. The budget s 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 x=(1,2,3) and y=(2,4,6). The cross-product sum is ∑xy=28 and the squared-input sum is ∑x2=14. Least squares gives slope 28/14=2.

Ridge adds the penalty strength to the denominator:

β^=∑xy∑x2+λ.

At λ=6, the slope is 28/20=1.4. At λ=14, it is 28/28=1. 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:

𝜷^=(𝐗⊤𝐗+λ𝐈)−1𝐗⊤𝐲.

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

  • Ridge adds the squared slope coefficients to RSS, weighted by the penalty strength.
  • A positive ridge penalty gives unique coefficients even with collinear inputs.
  • Ridge generally 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:

RSS+λ∑j=1p∣βj∣.

The intercept is unpenalized. The equivalent budget is ∑j∣βj∣≤s. For weights (3,−4), the L1 size is 3+4=7, while the squared L2 size is 9+16=25.

PropertyLasso, L1Ridge, L2
Penalty shape for two coefficientsDiamondCircle
Behavior near zeroConstant pull toward zeroPull weakens near zero
Feature selectionCan create exact zerosGenerally keeps nonzero weights
Correlated inputsOften retains one representativeOften 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 λ/2 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 λ/2.

For least-squares estimates (3.0,0.8,−1.5) and λ=2, the threshold is 1. The lasso returns (2.0,0,−0.5). Ridge instead divides each original coefficient by 1+λ=3, giving approximately (1.0,0.27,−0.5). 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:

12n∥𝐲−𝐗𝐰∥22+alpha∥𝐰∥1.

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

  • Lasso uses 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.
  • Lasso and 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:

12n∥𝐲−𝐗𝐰∥22+αρ∥𝐰∥1+α(1−ρ)2∥𝐰∥22.

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 (3,−4), 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 0.1(0.5)(7)=0.35. The L2 contribution is 0.1(0.5)(25)/2=0.625. The total penalty is 0.975.

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.

SettingPenalty effect
Smaller CStronger regularization
Larger CWeaker regularization
C=np.infNo regularization
l1_ratio=0L2
l1_ratio=1L1
0 < l1_ratio < 1Elastic 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.
  • LogisticRegression applies 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 0.001,0.01,0.1,1,10,100,1000. 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:

alphaMean MSEStandard error
0.0124.01.1
0.122.81.0
122.11.0
1022.91.1
10026.41.3

The minimum-error rule chooses alpha=1. The one-standard-error rule starts at the minimum and adds its standard error: 22.1+1.0=23.1. 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.
3

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

FamilyHow it selectsExample
FilterScores inputs before the final modelUnivariate F-test
WrapperFits models on candidate subsetsForward selection
EmbeddedSelects while fitting the modelLasso
Count the search before running it

Best subset selection fits every subset of p features, including the empty subset: 2p 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 1+p(p+1)/2 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 n rows and d features:

Radj2=1−(1−R2)n−1n−d−1.

With 50 rows, a five-feature model with R2=0.80 has adjusted R-squared about 0.777. A twelve-feature model with R2=0.83 scores about 0.775 after adjustment. The extra training fit does not cover the added complexity.

Mallows' criterion is:

Cp=RSSσ^2−n+2k,

where k counts coefficients including the intercept and σ^2 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 148/(50−13)=4 and its Cp is 37−50+26=13. The five-feature model has RSS about 174.1, giving Cp about 5.5.

AIC charges 2 per parameter; BIC charges log⁡n. For n>7, 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.
4

Engineer, 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 (0,1,0). 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:

ncyˉc+myˉnc+m.

Here nc is the category count and m is the smoothing strength. The overall target mean yˉ 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 (3+3)/14≈0.43. With 400 rows at the same rate, it is 303/410≈0.74.

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 a and b, degree-two polynomial expansion produces 1,a,b,a2,ab,b2. The squares allow curvature; the product allows the inputs to act jointly.

With p inputs and degree d, the count including the constant is (p+dd). 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
ConstructionUseful patternDecision to make
RatioDebt relative to incomeHandle a zero denominator
DifferenceDays since last purchaseDefine the prediction date
BinningStep-shaped effectsLearn bin edges on training rows
SplinesSmooth changes across rangesTune 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 h as:

(sin⁡2πh24,cos⁡2πh24).

Hour 23 is approximately (−0.259,0.966) and midnight is (0,1), about 0.26 apart. Noon is (0,−1), 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
MethodCalculationMain use
StandardizationSubtract training mean, divide by training SDComparable scales for linear models
Min-maxSubtract training minimum, divide by training rangeA chosen training interval
RobustSubtract training median, divide by IQRLess sensitivity to extreme values
Max-absoluteDivide by largest absolute training valueSparse 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 200≈14.14. The value 50 becomes (50−30)/14.14≈1.414.

Min-max scaling uses (x−10)/(50−10). 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 (60−30)/20=1.5. 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 log⁡(1+x) 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.
5

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

MechanismWhat missingness depends onExample
MCARNeither observed nor missing valuesRandom sensor dropouts
MARObserved informationRecorded age predicts a skipped answer
MNARThe missing value itselfHigher 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 0.9510≈0.60. 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.
  • ColumnTransformer applies 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

5 Walkthroughs

1

Diagnose a model before changing it

10 steps
Read paired errors, choose a remedy, and compute the effect of a penalty.
  1. 1
    IntroductionStart 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.

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

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

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

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

  6. 6
    ExplanationAdd a cost for coefficient size

    An L2 penalty makes large slopes expensive. For m rows, add λ∑jwj2/(2m) 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.

  7. 7
    ExampleCompute the two cost terms

    Use four errors: 1, −1, 2, and 0. Their squares total 6, so the fit term is 6/8=0.75. For weights (3, −2), the squared sizes total 13.

    At strength 1, the penalty is 13/8=1.625. Adding the two terms gives cost 2.375. This number evaluates this candidate weight vector; finding the fitted vector still requires minimizing the objective.

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

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

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

2

Follow coefficients from shrinkage to selection

17 steps
Work through ridge, lasso, elastic net, and a validation-based choice of strength.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionChoose what the penalty should achieve
  2. 2
    ExplanationRidge charges for squared slopes
  3. 3
    ExampleCalculate a no-intercept slope
  4. 4
    ChallengePredict a unit change
  5. 5
    ExplanationLasso can reach exactly zero
  6. 6
    ExampleFind the soft threshold
  7. 7
    ExampleApply the threshold to each coefficient
  8. 8
    ChallengeInterpret a disappearing feature
  9. 9
    ConnectionCombine sparsity with shared weights
  10. 10
    ExampleCompute a mixed penalty
  11. 11
    ChallengeMove logistic strength in the right direction
  12. 12
    TipSearch strengths with the scaler inside
  13. 13
    ExampleFind the minimum validation error
  14. 14
    ExampleChoose a close simpler candidate
  15. 15
    ChallengeCombine the selection and validation decisions
  16. 16
    Key InsightSeparate choosing from assessing
  17. 17
    RecapRead both the model and its evidence
3

Select features without selecting the validation result

11 steps
Compare subset searches, understand filter limits, and repair a leaking selection workflow.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTreat the feature list as a learned choice
  2. 2
    ExampleCount all subsets
  3. 3
    ExampleBuild a forward path
  4. 4
    Key InsightWhy training fit keeps rewarding inputs
  5. 5
    ExampleCount the intercept in Cp
  6. 6
    ChallengeJudge a higher training score
  7. 7
    ExplanationChoose a fast filter deliberately
  8. 8
    ExampleSee the interaction a filter misses
  9. 9
    ChallengeRepair target-based selection
  10. 10
    ChallengeCombine timing with stable selection
  11. 11
    RecapEvaluate the search as part of the model
4

Turn raw columns into useful model inputs

16 steps
Encode a category, construct features, and choose numeric mappings that preserve the intended relationships.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionGive the model a useful representation
  2. 2
    ExplanationDistinguish category order
  3. 3
    ExampleBuild indicators and choose a baseline
  4. 4
    ChallengePrepare for a new category
  5. 5
    ExampleSmooth a rare target mean
  6. 6
    TipKeep a row out of its own target encoding
  7. 7
    ExplanationMake a linear model represent a curve
  8. 8
    ExampleCount and scale the new columns
  9. 9
    ExamplePut a clock hour on a circle
  10. 10
    ChallengeMake an aggregate available at prediction time
  11. 11
    ExampleStandardize from stored statistics
  12. 12
    ExampleRead values beyond the training range
  13. 13
    ConnectionChange shape only when it helps
  14. 14
    ChallengeChoose the right preprocessing claim
  15. 15
    ChallengeCombine construction and scaling
  16. 16
    RecapMatch each change to a purpose
5

Build a pipeline that survives new data

15 steps
Prepare incomplete mixed-type rows, tune the full procedure, and preserve its learned mappings for prediction.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFollow a raw row through the model
  2. 2
    ExplanationInspect the gaps before filling them
  3. 3
    ExampleCompare a mean and a median
  4. 4
    ChallengeExplain the hidden cost of deletion
  5. 5
    TipChoose the order for distance-based filling
  6. 6
    ExplanationRoute numeric and category inputs
  7. 7
    ExampleAssemble the two branches
  8. 8
    ExampleTransform one incomplete future row
  9. 9
    ChallengeFind the validation boundary
  10. 10
    ExampleTune a nested preprocessing choice
  11. 11
    Key InsightRead the winning score correctly
  12. 12
    ChallengeKeep evaluation independent
  13. 13
    TipSave the fitted preparation with the predictor
  14. 14
    ChallengeRepair a changing prediction
  15. 15
    RecapKeep one procedure from fitting to use

Regularization and Feature Engineering practice questions

50 Practice Questions in 5 sets

Set 1: Read model fit and compare penalties10 Practice Questions

Question 1 of 10

A no-intercept regression has ∑xiyi=45 and ∑xi2=15. What ridge slope results under the objective RSS plus λβ2 at λ=10?
  1. 1.8
  2. 3.0
  3. 0.6
  4. 2.0
Show answerHide answer
Answer: A
The slope is 45/(15+10)=1.8 because ridge adds the strength to the squared-input denominator in this one-feature objective. The value 3.0 is the unpenalized slope, obtained by dividing 45 by 15 and ignoring the penalty.

Question 2 of 10

A classifier reaches 98% training accuracy and 73% validation accuracy. Its validation accuracy is inadequate for the task. What fitting problem does this pattern suggest?
  1. Underfitting the training data
  2. Overfitting to the training data
  3. A good fit with low variance
  4. A limit caused only by noise
Show answerHide answer
Answer: B
The classifier performs much better on familiar rows than on held-out rows, which signals overfitting. Underfitting would usually also show weak training performance; the high training accuracy here does not support that diagnosis.

Question 3 of 10

A constant baseline has validation RMSE 9.0. A straight-line model gives training/validation RMSE 8.5/8.7, while a quadratic on the same input gives 3.2/3.5. What explains the straight-line result?
  1. Its large variance causes overfitting.
  2. Its small error gap makes it adequate.
  3. Its limited flexibility causes underfitting.
  4. Its inputs contain no predictive signal.
Show answerHide answer
Answer: C
The quadratic learns a much better relationship from the same input and improves held-out error. That confirms the straight line is too simple. A small training–validation gap only shows similar performance on the two sets; it does not make errors near the baseline acceptable.

Question 4 of 10

For J=RSS/(2m)+λ∑jwj2/(2m), a fit has m=5, RSS 20, weights (2, −1), and λ=3. What is its total cost?
  1. 3.5
  2. 2.0
  3. 5.0
  4. 9.5
Show answerHide answer
Answer: A
The fit term is 20/10=2 and the squared weights sum to 5. The penalty is 3(5)/10=1.5, so the total is 3.5. Reporting 2.0 omits the regularization charge, even though it correctly computes the prediction-loss term.

Question 5 of 10

Two input columns are perfectly identical. What does a positive ridge penalty provide for their slope coefficients?
  1. Two independent measurements
  2. Exactly one nonzero coefficient
  3. An unbiased causal estimate
  4. A unique penalized solution
Show answerHide answer
Answer: D
A positive L2 penalty makes the slope objective strictly convex and yields a unique solution despite duplicate columns. It does not create independent information in those measurements. Exact feature removal is associated with L1 sparsity, not the usual behavior of ridge.

Question 6 of 10

With an identity feature matrix and no intercept, the lasso minimizes RSS plus λ∑∣βj∣. Least-squares coefficients are (−2.8, 0.4, 1.6) and λ=1.6. What coefficients result?
  1. (−1.2, 0, 0)
  2. (−1.08, 0.15, 0.62)
  3. (−2.0, 0, 0.8)
  4. (−3.6, 0, 2.4)
Show answerHide answer
Answer: C
The soft-threshold is λ/2=0.8: move each coefficient toward zero by 0.8 and clamp a crossed value to zero. This gives (−2.0, 0, 0.8). Subtracting 1.6 uses the wrong threshold for the stated RSS normalization.

Question 7 of 10

A logistic model overfits. If every other setting stays fixed, how does changing C from 8 to 0.08 change regularization?
  1. It makes the penalty weaker.
  2. It makes the penalty stronger.
  3. It switches from L2 to L1.
  4. It removes the intercept penalty.
Show answerHide answer
Answer: B
C is inverse regularization strength, so decreasing it strengthens the penalty. Treating C like the alpha parameter of ridge would reverse the conclusion. The change controls strength; it does not itself change the L1/L2 mixture.

Question 8 of 10

For weights (2, −3), an elastic net uses alpha 0.2 and l1_ratio 0.25. What is the total penalty under the scikit-learn elastic net objective?
  1. 2.200
  2. 0.900
  3. 0.575
  4. 1.225
Show answerHide answer
Answer: D
The L1 contribution is 0.2(0.25)(5)=0.25. The L2 contribution is 0.2(0.75)(13)/2=0.975, giving 1.225 in total. The value 2.200 omits the factor of one-half in the L2 term and therefore overcharges that component.

Question 9 of 10

Training and validation learning curves level off near a weak baseline. Adding rows barely changes either curve. Several more flexible models on the same inputs also fail to improve validation error. What should be investigated next?
  1. A much larger training sample alone
  2. Stronger penalties for every model
  3. More informative measurements or features
  4. The smallest training error achieved
Show answerHide answer
Answer: C
The flexible alternatives have already failed to reveal a useful pattern from these inputs, and more rows have brought little gain. Better measurements or features are therefore worth investigating. Labeling the original model as definitively underfit overlooks the evidence that capacity changes have not helped.

Question 10 of 10

Two highly correlated sensors alternate as the only retained member of a pair across lasso folds. Validation error barely changes. What is the most defensible conclusion?
  1. They may be substitutes; compare elastic net for stability.
  2. Each zero proves its sensor is unrelated to the outcome.
  3. The selected sensor is a cause; remove its counterpart.
  4. Each change proves a validation leak; increase alpha.
Show answerHide answer
Answer: A
The pair can carry overlapping signal, allowing lasso to choose either member with little predictive change. Elastic net is a useful comparison because its L2 component stabilizes correlated groups. A zero in one fold does not establish that the dropped sensor lacks a relationship with the target.
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

A ridge search has its lowest validation error at the largest alpha tried. What is the next useful search step?
  1. Choose the smallest alpha without testing.
  2. Choose alpha using the held-out test set.
  3. Stop because every larger alpha underfits.
  4. Extend the grid to larger alpha values.
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?
  1. 20
  2. 2
  3. 0.2
  4. 200
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A complete forward stepwise path is fitted for eight candidate features, counting the initial empty model. How many model fits are required?
  1. 256
  2. 37
  3. 36
  4. 9
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Why can ordinary training R-squared not fairly choose between nested least-squares models with different feature counts?
  1. It always falls as feature count increases.
  2. It already includes a penalty per feature.
  3. It cannot decrease when an input is added.
  4. It measures only the target variance.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A least-squares model uses 60 rows, four features, RSS 190, and a shared error-variance estimate σ^2=5. What is Mallows' Cp?
  1. −14
  2. 10
  3. −12
  4. 48
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A balanced dataset has two binary features. The target is 1 exactly when the features differ. Why can an individual-feature filter miss both inputs?
  1. Each input alone hides their predictive interaction.
  2. Each input has zero variance across the rows.
  3. The pair creates duplicate measurements of the target.
  4. The filter is fitting a complete two-feature model.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A team selects 15 columns using all available target labels, then runs five-fold cross-validation on a scaler-plus-classifier pipeline. Accuracy is unexpectedly high on a random-label check. What should change?
  1. Increase the classifier penalty after the same selection.
  2. Shuffle only the column order before cross-validation.
  3. Fit the selector once without the scaler and keep it fixed.
  4. Include the selector inside the cross-validated pipeline.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

An analyst wraps 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?
  1. StandardScaler fitted once before a larger LassoCV search
  2. GridSearchCV around StandardScaler followed by Lasso
  3. LassoCV followed by StandardScaler in the same pipeline
  4. LassoCV fitted to a scaler refitted on each validation part
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

With 70 rows, a five-feature model has R-squared 0.78 and a nine-feature model has R-squared 0.79. How do their adjusted R-squared values compare, rounded to three decimals?
  1. The nine-feature model leads: 0.759 versus 0.763.
  2. The five-feature model leads: 0.763 versus 0.759.
  3. They tie at 0.780 after adjusting for feature count.
  4. The nine-feature model leads: 0.790 versus 0.780.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A lab tries 200 penalty-and-feature settings on the same folds and reports the winning mean CV score as its final performance estimate. How should it estimate the full selection procedure more fairly?
  1. Average the winning score with its training score.
  2. Report the same folds with a narrower confidence band.
  3. Recompute the winner on the folds without its penalty.
  4. Use an untouched test set or outer cross-validation.
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

A linear model receives an unordered input with values "wire", "card", and "cash". What encoding avoids imposing a rank on the payment methods?
  1. Integer codes in alphabetical order
  2. The same numeric code for every method
  3. One-hot columns for the methods
  4. Integer codes in order of appearance
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

An encoder keeps all four training categories and uses handle_unknown="ignore". How does it encode a fifth, previously unseen category?
  1. Four zeros
  2. Five zeros
  3. An additional one-hot column
  4. The most frequent training category
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A target encoder uses overall mean 0.2 and smoothing strength 12. A category has six rows with mean target 0.8. What is its smoothed encoding?
  1. 0.8
  2. 0.5
  3. 0.2
  4. 0.4
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Four numeric inputs are expanded through degree two, including a constant. How many polynomial columns result?
  1. 14
  2. 15
  3. 16
  4. 10
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A StandardScaler fitted on training data is applied to a right-skewed column. What happens to that column's distribution shape?
  1. It becomes bell-shaped.
  2. It remains right-skewed.
  3. It becomes evenly spread.
  4. Its outliers are deleted.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A min-max scaler was fitted with minimum 20 and maximum 80. What does it return for a new value of 95 with the default unclipped mapping?
  1. 1.00
  2. 1.19
  3. 0.79
  4. 1.25
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A linear demand model performs poorly across midnight. Hour is its only time input, coded 0–23, and demand is strongly cyclical. What feature change directly represents the boundary relationship?
  1. Use both sine and cosine of the hourly angle.
  2. Standardize the single integer hour column only.
  3. Use only elapsed hours since the first training row.
  4. Use a squared hour column without any other change.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A customer-ID feature has many categories that appear only once. Training target encoding uses fit(X, y).transform(X) before the classifier is validated. What two changes address the main leakage risks?
  1. Increase smoothing and fit encodings on every target label.
  2. One-hot encode IDs once before making validation folds.
  3. Cross-fit training encodings within each outer training fold.
  4. Fit the encoder on each validation fold using its labels.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A maintenance model predicts failure at the start of each day. An engineer adds each machine's mean vibration over the entire recorded month, which includes later failures and later readings. Random validation improves sharply. What is the sound next step?
  1. Keep the monthly mean and increase the regularization strength.
  2. Scale the monthly mean separately on each validation fold.
  3. Keep the monthly mean because it contains no target column.
  4. Rebuild the aggregate from readings available by prediction time.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A regularized logistic model receives a skewed numeric input with valid zeros and negatives, plus an unordered category that may have new values at prediction. A team also wants a valid CV estimate. What preparation meets all three needs?
  1. Yeo-Johnson and unknown-safe one-hot encoding, fitted inside each fold
  2. Box-Cox and unknown-safe one-hot encoding, fitted inside each fold
  3. Yeo-Johnson and unknown-safe one-hot encoding, fitted before the folds
  4. Yeo-Johnson and default unknown-error one-hot encoding, fitted inside folds
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

A sensor column uses −777 to mean "not recorded". What should happen before fitting a usual median imputer that recognizes NaN?
  1. Convert −777 to a missing-value marker.
  2. Include −777 when estimating the median.
  3. Replace every negative reading with zero.
  4. Scale the column and keep −777 as observed.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Observed values are 3, 9, 11, and 81. What values would mean and median imputation respectively use for a gap?
  1. 10 and 26
  2. 26 and 10
  3. 26 and 11
  4. 24 and 10
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A pipeline uses KNNImputer on numeric columns whose ranges differ greatly. Where should a missing-value-compatible scaler go?
  1. After KNNImputer, fitted once on all rows
  2. Before KNNImputer, fitted only on test rows
  3. After the predictor, fitted in every fold
  4. Before KNNImputer, inside each training fold
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A ColumnTransformer lists numeric and categorical columns but leaves an extra identifier column unlisted. With its default remainder setting, what happens to that identifier?
  1. It passes through with its original values.
  2. It is converted into one-hot columns.
  3. It is dropped from the transformed output.
  4. It becomes the prediction target.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A grid tests three imputation strategies, two indicator settings, and five ridge strengths with four-fold CV. With the default final refit, how many fits occur?
  1. 120
  2. 121
  3. 31
  4. 600
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A search using neg_mean_squared_error reports best_score_ = −7.6. What MSE does this represent?
  1. 7.6
  2. −7.6
  3. 2.76
  4. 57.76
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A questionnaire records age for everyone. Missing responses to a second item depend on recorded age, but, within each age, not on the missing response. What missingness mechanism does this describe?
  1. Missing completely at random
  2. Missing not at random
  3. Missing at random
  4. A constant-value encoding
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A team learns medians and selects 12 columns from all labels before CV. It then scales within folds and tunes ridge. How should it obtain an independent estimate while keeping selection and preprocessing isolated?
  1. Nest a search over scaler–selector–ridge in outer CV using globally imputed rows
  2. Run a search over imputer–scaler–selector–ridge and report its winning inner score
  3. Nest a search over imputer–scaler–ridge in outer CV using the globally selected columns
  4. Nest a search over the raw-data imputer–scaler–selector–ridge pipeline in outer CV
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A saved one-feature model uses z=(x−50)/10 and prediction 4+2z. A service replaces only the scaler with its incoming batch mean 60 and SD 20. For x=70, what prediction should the saved procedure make, what does the changed service make, and what repairs it?
  1. 8; 5; refit only the scaler on a larger incoming batch
  2. 5; 8; reuse the stored scaler with the saved coefficients
  3. 8; 5; reuse the stored scaler with the saved coefficients
  4. 8; 6; keep batch scaling and use the original intercept
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A mixed-column pipeline must return pandas features, handle unseen nominal categories, and match a coefficient vector to its expanded inputs. What combination meets all three requirements?
  1. Dense one-hot output, an ignore-unknown policy, and fitted output feature names
  2. Sparse one-hot output, an ignore-unknown policy, and fitted output feature names
  3. Dense one-hot output, the default error-on-unknown policy, and fitted output names
  4. Dense one-hot output, an ignore-unknown policy, and raw input column names
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

A ridge model underfits because its slopes have been shrunk almost to zero. With its feature set fixed, what penalty change is a useful candidate?
  1. Increase alpha.
  2. Increase the test-set size.
  3. Decrease alpha.
  4. Penalize the intercept too.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A model needs sparse logistic coefficients with some stabilization across correlated predictors. For current scikit-learn, what is a compatible estimator setting?
  1. LogisticRegression(solver="lbfgs", l1_ratio=0.7)
  2. LogisticRegression(solver="saga", l1_ratio=0.7)
  3. LogisticRegression(solver="lbfgs", l1_ratio=1.0)
  4. LogisticRegression(solver="saga", l1_ratio=0.0)
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A feature-selection pipeline is correctly cross-validated. One retained column records the refund issued after a purchase is canceled, while prediction occurs at checkout. What should happen to that column?
  1. Remove it and reevaluate the procedure.
  2. Keep it because the selector was cross-validated.
  3. Keep it only after standardization.
  4. Use its validation median at prediction time.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A model y=b+aRIR+aBIB uses full red/blue indicators and has coefficients b=5, aR=3, and aB=−1. With no other inputs, what uniquely identified coefficients result after dropping blue as the baseline while preserving predictions?
  1. Intercept 5 and red coefficient 3
  2. Intercept 6 and red coefficient 2
  3. Intercept 8 and red coefficient −4
  4. Intercept 4 and red coefficient 4
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Logistic candidates have C values 0.01, 0.1, 1, and 10 with mean validation losses 0.47, 0.43, 0.42, and 0.425. The standard error at the minimum is 0.015. What does the one-standard-error rule choose?
  1. C = 1
  2. C = 10
  3. C = 0.01
  4. C = 0.1
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Five inputs independently have a 10% missing rate. One input is more likely to be missing at high unobserved values, even after accounting for other columns. The team drops every incomplete row and plans to predict on incomplete live rows. How should the plan be assessed?
  1. About 59% remain; the gaps are MCAR; live gaps still need a strategy
  2. About 59% remain; MNAR can bias deletion; live gaps still need a strategy
  3. About 90% remain; MNAR can bias deletion; live gaps still need a strategy
  4. About 59% remain; MNAR can bias deletion; deletion resolves live gaps
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A ridge model generates degree-two polynomial features from two raw inputs u and v, with include_bias=False. A colleague also wants an hourly feature that preserves the daily cycle. What feature count and preparation give a suitable representation?
  1. Seven; use both hour coordinates, then scale all generated numeric columns
  2. Six; use only the hour sine, then scale all generated numeric columns
  3. Eight; retain a polynomial constant and both hour coordinates, then scale
  4. Seven; use both hour coordinates, scaling only u and v before expansion
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

On the same data and fit criterion, forward selection chooses A first and then B, with RSS 120. Exhaustive search finds pair C,D with RSS 105. A full model has RSS 80, and an independent comparison favors C,D. What conclusion follows about the search and the deployed inputs?
  1. Forward search is invalid; deploy A,B because its path is nested
  2. The full model is best; deploy all inputs because RSS is 80
  3. Forward search missed a better pair; deploy C,D if they are available at prediction time
  4. The pair C,D must contain A; otherwise the exhaustive comparison is inconsistent
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A grid compares two imputation strategies, three retained feature counts, and four penalties within five-fold inner CV. The whole search is run in four outer folds, with refit=True each time. Excluding any later deployment fit, what fit count and score should be reported for the procedure?
  1. 480 fits; report outer-fold performance
  2. 484 fits; report outer-fold performance
  3. 484 fits; report the best inner-fold score
  4. 121 fits; report the mean training score
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A fitted ridge pipeline has output order: standardized length, standardized mass, then one-hot A, B, C. Length is measured in meters and mass in kilograms. Their training means are 10 and 4, with SDs 2 and 1. Coefficients are (2, −1, 3, 0, −2) and the intercept is 5. For length 12 m, mass 3 kg, and category C, what prediction and coefficient interpretation are correct?
  1. 4; the −2 weight belongs to category C, not a third raw numeric input
  2. 6; the −2 weight belongs to raw mass because it is the last measurement
  3. 24; the category expansion removes the need to standardize the numeric inputs
  4. 6; the −2 weight belongs to category C, not a third raw numeric input
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

91 Key Terms, each with its definition

A

Adjusted R-squared
Adjusted R-squared modifies training R-squared to account for the number of fitted input features relative to row count.
A larger model can raise ordinary R-squared yet lower adjusted R-squared when the improvement is too small.
Akaike information criterion
The Akaike information criterion, or AIC, balances model fit with a charge of two per estimated parameter in its usual form.
A small gain in fit may fail to justify an additional parameter when candidate models are compared by AIC.

B

Backward stepwise selection
Backward stepwise selection begins with the full input set and repeatedly removes one input according to the selected criterion.
A least-squares backward search needs an estimable full model before it can begin removing inputs.
Bayesian information criterion
The Bayesian information criterion, or BIC, balances model fit with a parameter charge equal to the logarithm of row count.
For one hundred rows, BIC charges more per extra parameter than the usual two-unit AIC charge.
Best subset selection
Best subset selection fits every possible subset of candidate inputs before comparing models of different sizes.
With twelve candidate inputs, the full search considers 4,096 subsets, including the empty model.
Bias
Bias is systematic prediction error from simplifying assumptions, measured relative to the true relationship.
A rigid straight-line model has high bias when the true response changes sharply with an input.
Binning
Binning converts a numeric range into intervals, allowing a model to use step-shaped effects while losing within-bin detail.
A fitted age-bin boundary must come from training data before the same bins are applied to new rows.
Box-Cox transformation
A Box-Cox transformation is a fitted power mapping that can reduce skew in a feature whose values are all strictly positive.
A column containing zero cannot be passed directly to Box-Cox without changing its defined input domain.

C

Coefficient path
A coefficient path shows how each fitted coefficient changes as the penalty strength varies across a sequence of values.
A lasso path reveals when an input becomes inactive and whether a correlated substitute takes its place.
Collinearity
Collinearity is an exact or approximate linear dependence among input columns that can make coefficient estimates unstable.
Two sensors with almost identical readings make it hard to separate their individual least-squares weights.
Column transformer
A column transformer applies different preprocessing branches to selected input columns and joins their transformed outputs.
Numeric measurements can be standardized while categorical columns are one-hot encoded in a separate branch.
Complete-case deletion
Complete-case deletion removes every row with a missing input, potentially losing many observations and changing the represented population.
Five mildly incomplete columns can leave far fewer usable rows than the observed share of any single column.
Coordinate descent
Coordinate descent is an iterative optimization method that updates one coefficient at a time while holding the others fixed.
Lasso fitting cycles through coefficients until the updates meet the solver's convergence requirements.
Cross fitting
Cross fitting constructs training-row encodings using information learned from other folds, excluding each row's own target.
TargetEncoder.fit_transform makes a training row's encoded value without using its own outcome in the category mean.
Cyclical encoding
Cyclical encoding maps a repeating quantity to circular coordinates so values near the end and start remain close.
Sine and cosine hour features place 23:00 near midnight while keeping noon on the opposite side.

D

Data leakage
Data leakage occurs when fitting or selection uses information that would be unavailable for the predictions being evaluated.
Selecting columns using validation labels leaks those outcomes into the feature set later scored on that fold.
Dummy-variable trap
The dummy-variable trap is the collinearity created when full category indicators sum to an intercept column in a linear model.
Dropping a named baseline category yields identifiable unregularized contrasts against that baseline.

E

Elastic net
Elastic net is a penalized linear method combining absolute and squared coefficient charges to support sparsity and stability.
Elastic net is a useful candidate when several correlated measurements should share predictive weight.
Embedded selection
Embedded selection chooses inputs as part of fitting a predictive model, through coefficients or learned importance values.
Lasso performs embedded selection because its fitted zero coefficients remove features during optimization.

F

Feature engineering
Feature engineering constructs useful predictor inputs from raw data and domain knowledge to express relationships a model can learn.
Multiplying a plot's frontage by its depth creates an area feature for a model that predicts value.
Feature-name propagation
Feature-name propagation carries column identities through preprocessing so transformed inputs can be matched to fitted model coefficients.
An encoded neighborhood indicator has its own output name and coefficient instead of sharing one raw-column position.
Filter selection
Filter selection ranks or removes inputs using feature statistics before the final predictive model is fitted.
A univariate filter can quickly reduce thousands of columns before comparing more expensive estimators.
Fit
Fit is the learning operation that estimates parameters or stores statistics from the supplied training observations.
The imputer's fit learns a median, while the final estimator's fit learns its predictive coefficients.
Forward stepwise selection
Forward stepwise selection starts with no inputs and repeatedly adds the single remaining input that improves the chosen score most.
The best first input stays in the forward path even if a later exhaustive search favors a pair without it.
Frequency encoding
Frequency encoding replaces a category with its count or proportion in training data, avoiding one indicator per category.
A product category occurring in 2% of training rows can receive that stored proportion on new rows.

G

Generalization
Generalization is a fitted model's ability to predict observations that were not used to learn its parameters.
A delivery-time model generalizes well when its error stays acceptable on held-out deliveries.
Grid search
Grid search fits and validates the specified combinations of hyperparameter values to compare complete candidate procedures.
Three imputation settings and four strengths create twelve combinations before accounting for validation folds.
Grouping effect
The grouping effect is elastic net's tendency to retain correlated inputs together and distribute predictive weight among them.
Several related sensor measurements can remain active together instead of one replacing the others.

H

High cardinality
High cardinality means that a categorical input has many distinct values, often producing a large and sparse indicator matrix.
Thousands of product IDs can make a full one-hot representation costly and leave many categories rarely observed.
Hyperparameter
A hyperparameter is a setting chosen outside the coefficient-fitting step, usually by validation over candidate values.
Penalty strength is a hyperparameter, while the fitted slopes are learned separately for each candidate.

I

Input contract
An input contract specifies the column names and compatible data types expected by a fitted prediction procedure.
A new batch must provide the same raw measurement columns so each stored preprocessing branch receives its inputs.
Interaction feature
An interaction feature combines inputs so that a model can represent one input's effect changing with another input.
A temperature-times-insulation term can represent different heating responses for different insulation levels.
Intercept
The intercept is the constant prediction component when all model input features are zero, normally excluded from slope penalties.
With centered inputs and strongly shrunk slopes, the intercept preserves the overall target level.
Inverse regularization strength
Inverse regularization strength is a parameter whose decrease strengthens the penalty, used as C in logistic regression.
Reducing C from 5 to 0.05 strengthens logistic shrinkage even though the numeric setting becomes smaller.
Iterative imputation
Iterative imputation models each incomplete feature from other inputs and cycles through those predictions for several rounds.
A repeated regression-based fill may improve on a constant median when other measurements predict the missing input.

K

KNN imputation
KNN imputation estimates a missing input using nearby training rows, with similarity measured through their available feature values.
Scaling before KNN imputation prevents a large-range measurement from dominating the neighbor search.

L

L1 penalty
An L1 penalty charges for the sum of absolute slope coefficients, applying a constant pull toward zero away from its corner.
Small fitted effects can disappear entirely under L1 even when L2 would leave them with nonzero weights.
L2 penalty
An L2 penalty charges for the sum of squared slope coefficients, making a few large weights especially expensive.
Weights of 4 and 0 incur a larger squared-size charge than weights of 2 and 2 with the same total.
Lasso
The lasso is a penalized linear method using absolute coefficient size, allowing some fitted slopes to become exactly zero.
A lasso model can remove redundant measurements and reduce the number of inputs collected at prediction time.
Learning curve
A learning curve plots training or validation performance as the number of training observations changes.
A validation curve that improves as rows are added supports collecting more comparable training data.
Log transformation
A log transformation compresses positive values and turns multiplicative changes into additive differences on the transformed scale.
Successive doublings have equal spacing after taking logarithms, even when their raw differences grow.
Logarithmic grid
A logarithmic grid is a set of candidate values spaced by multiplicative factors to explore several orders of magnitude.
Strengths 0.01, 0.1, 1, 10, and 100 test a wider range than five nearby values around one.

M

Mallows' Cp
Mallows' Cp is a least-squares model criterion combining scaled RSS with a charge for coefficients, including the intercept.
A shared error-variance estimate lets Cp compare the fit improvement against the cost of extra coefficients.
MAR
Missing at random means missingness depends on observed information, with no further dependence on the missing value after conditioning.
A skipped response can be MAR when its probability depends on recorded age but not the response within each age.
Max-absolute scaling
Max-absolute scaling divides a feature by its largest absolute training value, preserving zero entries in sparse data.
A sparse numeric column can be rescaled without turning every stored zero into a nonzero value.
MCAR
Missing completely at random means the probability of a gap is unrelated to observed values or to the value that is missing.
Random communication dropouts can produce MCAR sensor gaps when they do not depend on the readings.
Min-max scaling
Min-max scaling maps values using the training minimum and range, usually placing the observed training range between zero and one.
A future measurement above the stored maximum can map to 1.3 without any error in the transformation.
Missing indicator
A missing indicator is a binary input that records whether an original value was missing before it was imputed.
Two rows with the same numeric fill can receive different predictions when their missing indicators differ.
Mixing ratio
The mixing ratio specifies the relative L1 contribution in elastic net, with the remaining contribution assigned to L2.
An l1_ratio of 0.8 favors L1 while retaining an L2 component to stabilize correlated feature groups.
MNAR
Missing not at random means the chance of a gap still depends on the missing value after accounting for observed information.
Income reporting can be MNAR when people with higher unreported incomes are less likely to provide them.
Model complexity
Model complexity is the range of relationships a model can represent, also called its capacity or flexibility.
Increasing polynomial degree expands model complexity by allowing more changes in the fitted curve.
Model persistence
Model persistence saves a fitted predictive procedure so its learned preprocessing and estimator can be loaded for later use.
Persisting the whole pipeline preserves category columns and scaling statistics along with the coefficients.
Mutual information
Mutual information measures statistical dependence and can detect relationships beyond the linear associations captured by basic scores.
A curved feature–target relationship may carry mutual information even when its linear correlation is small.

N

Negative error score
A negative error score changes an error metric's sign so that maximizing the score selects a smaller prediction error.
A negative MSE score of −6 is better than −9 because its corresponding positive MSE is smaller.
Nested cross-validation
Nested cross-validation uses an inner loop to tune settings and an outer loop to evaluate the complete tuning procedure.
Outer-fold scores assess predictions for rows that did not help choose the penalty or preprocessing settings.
Nominal variable
A nominal variable identifies categories without a meaningful order, so numerical ranks can add a false relationship.
Payment types are nominal because a card payment is not inherently above or below a bank transfer.

O

One-hot encoding
One-hot encoding represents a category with a separate binary indicator for each fitted category value.
The value "green" activates its own indicator while the red and blue indicators remain zero.
One-standard-error rule
The one-standard-error rule selects the simplest candidate within one standard error of the minimum mean validation error.
A stronger ridge penalty can be chosen when its error is close enough to the best candidate's mean.
Ordinal variable
An ordinal variable has categories with a meaningful order, although the distances between consecutive levels need not be equal.
Small, medium, and large have an order that should be given explicitly when fitting an ordinal encoder.
Overfitting
Overfitting occurs when a model fits training-specific details, including noise, that transfer poorly to new rows.
A deep tree can have tiny training error while making much larger errors on validation observations.

P

Penalty strength
Penalty strength is the nonnegative multiplier controlling how much coefficient size contributes to a regularized objective.
A ridge search compares several alpha values to find a useful amount of shrinkage on held-out folds.
Pipeline
A pipeline is an ordered chain of fitted transformations ending in an estimator, reused as one training and prediction procedure.
Calling predict on the saved pipeline repeats its stored imputation and encoding before the model predicts.
Polynomial feature
A polynomial feature is a power or product of original numeric inputs that lets a linear-in-coefficients model represent curves.
Adding a squared temperature term allows the fitted response to bend as temperature changes.

Q

Quantile transformation
A quantile transformation maps empirical ranks to a chosen distribution, changing spacing and reducing the influence of extremes.
A normal-output quantile mapping reshapes a skewed column but also changes the distances between readings.

R

Random state
A random state fixes the pseudorandom sequence used by a shuffled splitter or randomized estimator for repeatable runs.
Using the same integer seed reproduces a shuffled split when the data and software behavior are unchanged.
Ratio feature
A ratio feature divides one measurement by another to express a relative quantity, requiring a defined zero-denominator policy.
Debt divided by income measures relative burden, with zero-income cases handled through an explicit rule.
Recursive feature elimination
Recursive feature elimination repeatedly fits a model and removes inputs with the smallest coefficient magnitudes or importances.
Coefficient-based RFE needs comparable input scales so numeric units do not determine the elimination order.
Refit
Refit is the final fitting of the selected candidate on all available training rows after its hyperparameters have been chosen.
GridSearchCV refits the winning pipeline by default, making best_estimator_ ready for held-out prediction.
Regularization
Regularization adds a cost for parameter size or complexity to the fitting objective to control model flexibility.
A penalty can accept a small increase in training error when it prevents a much less stable fit.
Reproducibility
Reproducibility is the ability to rerun a recorded modeling procedure with its data and software context and obtain consistent results.
Pinned versions and a recorded data snapshot complement random seeds when reproducing a model comparison.
Residual sum of squares
The residual sum of squares is the total of the squared differences between observed targets and fitted predictions.
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
Robust scaling centers on the training median and divides by the interquartile range to limit outlier influence on the scale.
An extreme observed income changes a mean-based scale more than a median-and-quartile-based scale.
Row normalization
Row normalization rescales each observation vector to unit length, treating rows individually instead of scaling feature columns.
Normalizer changes the magnitude of a row vector without estimating a separate mean for each input column.

S

Selection stability
Selection stability describes how consistently a feature is retained across different training samples or validation folds.
Counting retention across folds can reveal that a correlated feature pair is interchangeable in the fitted models.
Shrinkage
Shrinkage is the deliberate movement of fitted coefficients toward zero through a penalty on their size.
A shrunken coefficient can make training predictions less exact while improving held-out accuracy.
Simple imputation
Simple imputation replaces a missing input with a fixed column value such as a training mean, median, mode, or chosen constant.
A median learned from the training rows fills numeric gaps in both validation and later prediction rows.
Soft thresholding
Soft thresholding moves a value toward zero by a fixed amount and returns zero if that move would cross or reach zero.
When a lasso design matrix is the identity, a least-squares slope smaller than the threshold is removed.
Solver
A solver is the numerical procedure that minimizes a model's objective, with supported penalties depending on the algorithm.
A logistic elastic net fit needs a compatible solver such as saga instead of the default L2-only lbfgs.
Sparse matrix
A sparse matrix stores mostly nonzero entries and their positions, saving memory when a transformed table contains many zeros.
OneHotEncoder uses sparse output by default because each row activates only a small share of category columns.
Sparse model
A sparse model has many coefficients equal to zero and makes its predictions using only the remaining active features.
A model with five active slopes out of two hundred candidate inputs is sparse in its coefficient representation.
Spline
A spline is a function assembled from polynomial pieces, used to represent smooth variation across different input ranges.
Spline features can model a smooth change in energy use without one high-degree global polynomial.
Standardization
Standardization subtracts a feature's training mean and divides by its training standard deviation to give a comparable scale.
A standardized value of two represents a measurement two training standard deviations above the mean.

T

Target encoding
Target encoding replaces a category with a target-based statistic, commonly a smoothed category mean learned without row leakage.
A rare category's estimated outcome rate is pulled toward the global rate to reduce unstable extreme values.
Transform
Transform applies a previously learned mapping to input rows without refitting its stored statistics on those rows.
Validation measurements use the training scaler's mean when transform prepares them for prediction.

U

Underfitting
Underfitting occurs when a model lacks the flexibility needed to capture a learnable pattern in its inputs.
A straight line underfits a curved pattern that a quadratic learns with much lower validation error.
Univariate score
A univariate score measures one feature's relationship with the target without assessing its joint role with other inputs.
Two near-duplicate measurements can both receive high scores even though they provide redundant signal.

V

Variance
Variance measures how much fitted predictions would change across different training samples from the same population.
Unstable coefficients across repeated samples suggest variance that a shrinkage penalty may reduce.

W

Weight decay
Weight decay is the shrinkage of an existing coefficient through a multiplicative factor in an L2 gradient update.
Each regularized update slightly reduces the current weight before adding the error-gradient contribution.
Wrapper selection
Wrapper selection compares feature sets by repeatedly fitting and scoring the intended predictive estimator on those sets.
Sequential feature selection evaluates candidate additions through the estimator's validation performance.

Y

Yeo-Johnson transformation
A Yeo-Johnson transformation is a fitted power mapping that can reshape numeric data including valid zeros and negative values.
PowerTransformer can compare a skewed signed measurement using Yeo-Johnson inside each training fold.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started