Imputation, Encoding and Scaling, Chosen by Model Family
Choose imputation, categorical encoding (one-hot, ordinal, target) and scaling by what the model does with numbers: measured runs show where linear and distance-based models need each step, and where tree models ignore it.
Contentsand lesson path
On this page
- Why it matters
- Imputation: what goes in the gaps
- Encoding categories: one-hot, ordinal and target
- Scaling: needed by some models, ignored by trees
- Check your understanding
- Apply it
- Review prompt
Lessons of Data Preparation & Feature Engineering
- Auditing Raw Data Before You Model Concept · 20 min
- Imputation, Encoding and Scaling, Chosen by Model Family Concept · 25 min
- Worked Example: Features from Timestamps, Text and Group Aggregates Worked example · 25 min
- Lab: One Pipeline from Raw Rows to Predictions Lab · 30 min
- Worked Example: Building a Point-in-Time-Correct Training Set Worked example · 20 min
- Check: Preparing Data the Same Way Twice Knowledge check · 8 questions
What you will learn
- Choose and apply imputation, categorical encoding (one-hot, ordinal, target) and scaling strategies appropriate to the model family.
01. Why it matters
The same raw table needs different preparation for different models, because models read numbers in different ways. Two families cover most tabular work.
- Linear and distance-based models, such as logistic regression, support vector machines, k-nearest neighbours and neural networks, combine features arithmetically. A linear model multiplies each feature by one coefficient and adds the results; k-nearest neighbours measures distances between rows. For them the size of the numbers matters, missing values are not allowed, and a category must become numbers that do not imply a false order.
- Tree-based models, such as decision trees, random forests and gradient boosting, ask yes/no questions about one feature at a time: is the distance above 18.4 km? For them only the order of a feature's values matters, and scikit-learn's histogram gradient boosting models accept missing values directly.
This lesson takes three preparation decisions in turn, imputation, encoding and scaling, and measures which ones matter for which family. Every transformer here follows scikit-learn's contract: fit learns something from training data, such as a median, a list of categories or a mean, and transform applies it. Fitting only on training rows keeps the evaluation honest; lesson 4 enforces that with a pipeline. Tested with Python 3.12, NumPy 2.5, pandas 3.1 and scikit-learn 1.9.
02. Imputation: what goes in the gaps
Imputation replaces a missing value with an estimate. SimpleImputer offers four strategies: the column's mean; its median, which is safer when the column is skewed or has outliers; its most_frequent value, which also works for text; or a constant you choose. With add_indicator=True it also appends a 0/1 missing-indicator column.
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
train = pd.DataFrame({"weight_kg": [1.2, np.nan, 3.0, 2.2, np.nan, 0.8],
"distance_km": [12.0, 30.5, 8.1, 19.0, 25.4, 40.2]})
test = pd.DataFrame({"weight_kg": [np.nan, 5.0], "distance_km": [np.nan, 14.0]})
imp = SimpleImputer(strategy="median", add_indicator=True)
imp.set_output(transform="pandas")
imp.fit(train) # the medians are learned here, from training rows only
print("learned medians:", imp.statistics_.round(2).tolist())
print(imp.transform(test))learned medians: [1.7, 22.2]
weight_kg distance_km missingindicator_weight_kg
0 1.7 22.2 1.0
1 5.0 14.0 0.0Two details here matter later. The fill values come from the training rows only: the test row with a missing distance gets 22.2, the training median, whatever the test set contains. And there is an indicator for weight_kg but none for distance_km, because indicators are created only for columns that had gaps during fit. The distance gap is still filled, because the imputer was fitted on that column. A column that goes through no imputer at all would reach the model as NaN, and lesson 4 shows that failure.
Is the indicator worth having? It is when the fact that a value is missing says something about the target. The next script simulates that: rural addresses often fail to geocode, and rural parcels are late more often.
import numpy as np
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(3)
n = 10_000
distance = rng.gamma(2.0, 9.0, n)
rural = rng.random(n) < 0.15 # rural addresses often fail
logit = -1.5 + 0.03 * distance + 1.5 * rural # to geocode, and run late
y = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
X = distance.reshape(-1, 1).copy()
X[rural & (rng.random(n) < 0.7)] = np.nan # 70% of rural rows lose distance
print(f"missing: {np.isnan(X).mean():.1%} of rows")
models = {
"logistic, median": make_pipeline(SimpleImputer(strategy="median"),
LogisticRegression()),
"logistic, median + flag": make_pipeline(
SimpleImputer(strategy="median", add_indicator=True), LogisticRegression()),
"hist gradient boosting, NaN as is": HistGradientBoostingClassifier(
max_depth=3, random_state=0),
}
for name, model in models.items():
auc = cross_val_score(model, X, y, cv=5, scoring="roc_auc")
print(f"{name:<34} CV AUC {auc.mean():.3f}")missing: 10.6% of rows
logistic, median CV AUC 0.593
logistic, median + flag CV AUC 0.647
hist gradient boosting, NaN as is CV AUC 0.644The median alone hides the signal, because a missing distance turns into an ordinary-looking 15 km. The indicator gives the linear model a separate coefficient for "distance unknown", and the cross-validated AUC rises from 0.593 to 0.647. Histogram gradient boosting reaches the same level with no imputation: at each split it learns which side the missing values should go to. Model-based imputers such as KNNImputer and IterativeImputer predict a missing value from other columns; with a strong model, simple imputation often does as well, so start simple and measure.
03. Encoding categories: one-hot, ordinal and target
Models need numbers, so a categorical column must be encoded. A nominal category has no natural order (depot, colour, zone); an ordinal one does (S < M < L < XL). Three encoders cover most cases:
OneHotEncodermakes one 0/1 column per category. It never invents an order, but it adds a column for every category.OrdinalEncoderreplaces each category with one integer. It is compact, but integers carry an order and a spacing.TargetEncoderreplaces each category with a smoothed mean of the target for that category: one numeric column, however many categories there are.
What goes wrong with integers for a nominal column depends on the model. Four delivery zones with very different late rates show it.
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder
from sklearn.tree import DecisionTreeClassifier
rng = np.random.default_rng(0)
rate = {"east": 0.40, "north": 0.10, "south": 0.45, "west": 0.12} # true late rates
zone = rng.choice(list(rate), 4_000)
y = (rng.random(4_000) < pd.Series(zone).map(rate)).astype(int)
X = pd.DataFrame({"zone": zone})
grid = pd.DataFrame({"zone": list(rate)})
models = {
"linear + ordinal": make_pipeline(OrdinalEncoder(), LogisticRegression()),
"linear + one-hot": make_pipeline(OneHotEncoder(), LogisticRegression()),
"tree + ordinal": make_pipeline(OrdinalEncoder(),
DecisionTreeClassifier(max_depth=3)),
}
codes = OrdinalEncoder().fit_transform(grid)[:, 0].astype(int)
print("zone codes:", dict(zip(rate, codes.tolist())))
print(f"{'':<17}" + "".join(f"{z:>7}" for z in rate))
print(f"{'observed rate':<17}" + "".join(f"{y[zone == z].mean():>7.2f}" for z in rate))
for name, model in models.items():
p = model.fit(X, y).predict_proba(grid)[:, 1]
print(f"{name:<17}" + "".join(f"{v:>7.2f}" for v in p))zone codes: {'east': 0, 'north': 1, 'south': 2, 'west': 3}
east north south west
observed rate 0.39 0.10 0.45 0.12
linear + ordinal 0.34 0.29 0.24 0.20
linear + one-hot 0.39 0.10 0.45 0.12
tree + ordinal 0.39 0.10 0.45 0.12The ordinal encoder sorted the zones alphabetically, east = 0 to west = 3. A linear model gives that column one coefficient, so its predictions can only move in one direction along 0, 1, 2, 3: it predicts 0.34, 0.29, 0.24 and 0.20 for observed rates of 0.39, 0.10, 0.45 and 0.12. One-hot encoding gives every zone its own coefficient and recovers the rates. A tree on the same integer codes recovers them too, because it can cut the code range several times. So integer codes for nominal categories are a poor fit for linear models and usually acceptable for trees. For a truly ordered category, ordinal encoding suits both families, but state the order yourself.
import pandas as pd
from sklearn.preprocessing import OrdinalEncoder
sizes = pd.DataFrame({"box_size": ["M", "XL", "S", "L", "M"]})
default = OrdinalEncoder().fit(sizes)
print("default order:", default.categories_[0].tolist())
explicit = OrdinalEncoder(categories=[["S", "M", "L", "XL"]]).fit(sizes)
print("explicit order:", explicit.categories_[0].tolist())
print("codes:", explicit.transform(sizes)[:, 0].astype(int).tolist())default order: ['L', 'M', 'S', 'XL']
explicit order: ['S', 'M', 'L', 'XL']
codes: [1, 3, 0, 2, 1]Left to itself, OrdinalEncoder sorts labels as strings: L, M, S, XL. Passing categories fixes the order.
One-hot encoding struggles with high cardinality: a column with thousands of distinct values, such as a sender ID, becomes thousands of mostly-zero columns, many for categories seen only a few times. Target encoding compresses it into one number per category, but it reuses the label, which brings two risks. If a row's encoding includes its own target, the feature leaks the answer. And a category seen twice gets an extreme mean, 0 or 1, that reflects luck more than the category.
import numpy as np
import pandas as pd
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, train_test_split
from sklearn.preprocessing import TargetEncoder
rng = np.random.default_rng(1)
n = 6_000
sender = rng.integers(0, 2_000, n) # 2,000 senders, about 3 rows each
quality = rng.normal(0, 0.5, 2_000) # a weak real effect per sender
p = 1 / (1 + np.exp(-(-1.0 + quality[sender])))
y = (rng.random(n) < p).astype(int)
X = pd.DataFrame({"sender_id": sender.astype(str)})
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0)
# Naive: each sender's mean target on the training rows, own row included
means = pd.Series(y_tr, index=X_tr.index).groupby(X_tr["sender_id"]).mean()
naive_tr = X_tr["sender_id"].map(means)
naive_te = X_te["sender_id"].map(means).fillna(y_tr.mean())
print(f"naive encoding train AUC {roc_auc_score(y_tr, naive_tr):.3f}"
f" test AUC {roc_auc_score(y_te, naive_te):.3f}")
# Cross fitting: fit_transform encodes each fold with means from the other folds
enc = TargetEncoder(cv=StratifiedKFold(5, shuffle=True, random_state=0))
te_tr = enc.fit_transform(X_tr, y_tr)[:, 0]
te_te = enc.transform(X_te)[:, 0]
print(f"TargetEncoder train AUC {roc_auc_score(y_tr, te_tr):.3f}"
f" test AUC {roc_auc_score(y_te, te_te):.3f}")
# Smoothing: how far is a sender seen once pulled towards the global mean?
counts = X_tr["sender_id"].value_counts()
once = counts[counts == 1].index[0]
print(f"sender {once}: 1 training row, raw mean {means[once]:.2f},"
f" global mean {enc.target_mean_:.2f}")
for smooth in ["auto", 20.0]:
enc_s = TargetEncoder(smooth=smooth).fit(X_tr, y_tr) # fit() only to inspect
i = list(enc_s.categories_[0]).index(once)
print(f" smooth={smooth!s:<5} stored encoding {enc_s.encodings_[0][i]:.2f}")naive encoding train AUC 0.902 test AUC 0.552
TargetEncoder train AUC 0.544 test AUC 0.551
sender 29: 1 training row, raw mean 0.00, global mean 0.27
smooth=auto stored encoding 0.00
smooth=20.0 stored encoding 0.26The naive version computes each sender's mean on the training rows, own row included: AUC 0.902 on training rows, 0.552 on test rows. A model would learn to trust a feature that mostly memorised labels. TargetEncoder.fit_transform uses cross fitting: it splits the training rows into folds and encodes each fold with means learned on the other folds, so no row sees its own label. Its training AUC, 0.544, matches the test value, which is what an honest feature looks like. Call fit_transform on training data; fit then transform on the same rows skips the cross fitting. A pipeline does this for you. In scikit-learn 1.9 the shuffle and random_state parameters of TargetEncoder are deprecated: pass a splitter as cv, as the script does.
Smoothing blends a category's mean with the global mean, giving the category's own mean the weight n / (n + m), where n is its row count and m the smoothing strength. The default smooth='auto' estimates m from the variance of the target inside the category. The last lines show a catch: a sender seen once has no variance, so its encoding is not pulled in at all and stays at 0.00, while smooth=20.0 gives 0.26, near the global 0.27. For binary targets with many tiny categories, compare a fixed smoothing value with 'auto' by cross-validation.
04. Scaling: needed by some models, ignored by trees
Scaling changes the units of numeric features. StandardScaler subtracts the mean and divides by the standard deviation; MinMaxScaler maps the training range to 0 to 1; RobustScaler uses the median and the IQR, so a few outliers barely move it.
Models that measure distances or penalise coefficients need it. k-nearest neighbours adds up squared differences, so a feature measured in hundreds drowns one measured in tenths. Regularised linear models, and scikit-learn's LogisticRegression is regularised by default, shrink all coefficients by one rule, so a feature's units decide how hard it is penalised. Trees do not care, because a split only asks whether a value is above a threshold.
import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer, StandardScaler
from sklearn.tree import DecisionTreeClassifier
X, y = load_wine(return_X_y=True)
print("feature ranges: min", X.min(axis=0).min(), "max", X.max(axis=0).max())
knn = KNeighborsClassifier()
print(f"kNN raw CV accuracy {cross_val_score(knn, X, y, cv=5).mean():.3f}")
scaled = make_pipeline(StandardScaler(), knn)
print(f"kNN scaled CV accuracy {cross_val_score(scaled, X, y, cv=5).mean():.3f}")
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)
base = DecisionTreeClassifier(random_state=0).fit(X_tr, y_tr).predict(X_te)
for name, step in [("standardised", StandardScaler()),
("log1p", FunctionTransformer(np.log1p))]:
tree = make_pipeline(step, DecisionTreeClassifier(random_state=0))
same = np.array_equal(tree.fit(X_tr, y_tr).predict(X_te), base)
print(f"tree on {name:<12} same test predictions as raw: {same}")feature ranges: min 0.13 max 1680.0
kNN raw CV accuracy 0.691
kNN scaled CV accuracy 0.949
tree on standardised same test predictions as raw: True
tree on log1p same test predictions as raw: TrueThe wine features range from 0.13 to 1,680. Unscaled, k-nearest neighbours is dominated by the largest feature and reaches 0.691 accuracy; standardised, 0.949. The decision tree makes identical test predictions on raw, standardised and log-transformed inputs. Any strictly increasing transformation keeps the order of a feature's values, so the tree finds the same partitions of the training rows. One subtlety: a tree puts its threshold halfway between two neighbouring training values, so after a nonlinear transformation such as a log, a new value that falls between them can occasionally land on the other side. Affine scaling (multiply and add, as StandardScaler does) gives the same predictions up to floating-point rounding.
Put together, sensible starting points are:
- linear and distance-based models: median imputation with an indicator, one-hot encoding for nominal columns, ordinal encoding with an explicit order for ordered ones, target encoding for very high cardinality, and scaling;
- tree ensembles: native missing-value support where the model has it (an imputer with an indicator otherwise), ordinal or target encoding, and no scaling.
Treat these as defaults to test with cross-validation, not as rules.
05. Check your understanding
06. Apply it
In your practice dataset, decide the preparation for two model families and test the decisions.
- Build a logistic regression pipeline with median imputation plus indicators, one-hot encoding and
StandardScaler, and aHistGradientBoostingClassifierpipeline with ordinal encoding, no imputation and no scaling. - Cross-validate both with the same folds. Then remove one step at a time (the indicators, the scaler, the one-hot encoder in favour of ordinal codes) and record which changes move which model's score.
- If you have a column with hundreds of categories or more, compare one-hot encoding with
TargetEncoderusingsmooth='auto'and a fixed value such as 20.
Keep the results table: it is the evidence for your final pipeline.
07. Review prompt
Without looking back, answer in your own words:
- Why did the missing indicator raise the linear model's AUC, and why did histogram gradient boosting not need it?
- What does a linear model do with an ordinal code for a nominal column, and why does a tree cope with the same code?
- What two problems does
TargetEncoderaddress with cross fitting and with smoothing? - Why does
StandardScalerchange k-nearest neighbours but not a decision tree?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.