Sub topic 8
Keeping the Missingness Signal with Indicator Columns
This chapter assumes you can fit a SimpleImputer, read statistics_, and use a Pipeline. It covers what imputation hides from a model and how add_indicator restores it.
What imputation throws away
After imputation, a filled-in value looks exactly like a measured one. A model cannot tell whether an income of 52,000 was recorded or computed from the column median.
Sometimes that difference matters. Missing values often carry information:
- A customer who leaves the income field blank may differ from one who fills it in.
- A lab test that was never ordered may mean the doctor judged it unnecessary.
- A sensor that returns nothing may be failing, and failure may predict the outcome.
In statistics this is called informative missingness. If the missingness itself predicts the target, imputing alone discards that signal.
Adding indicator columns
Setting add_indicator=True makes SimpleImputer append one binary column per feature that had missing values. A 1 means the entry was missing in that row. A 0 means it was observed.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([[1.0, 2.0],
[np.nan, 3.0],
[7.0, np.nan]])
imputer = SimpleImputer(strategy="constant", fill_value=0, add_indicator=True)
print(imputer.fit_transform(X))
# [[1. 2. 0. 0.]
# [0. 3. 1. 0.]
# [7. 0. 0. 1.]]The output has four columns. The first two are the imputed features. The last two are indicators for column 0 and column 1. Row 1 has a 1 in the third column because its first feature was missing. Row 2 has a 1 in the fourth column because its second feature was missing.
Which columns get an indicator
By default, only columns that contained missing values during fit get an indicator. This keeps the output narrow. If the training data has no missing values in a column, that column gets no indicator.
This creates a failure mode. Suppose a column is complete in training but has NaN at prediction time. The fitted imputer has no indicator for it, and the output width stays fixed. Because the column also had no missing values at fit time, the imputer learned a fill value for it anyway, so the NaN is filled, but the model never sees a signal. Check that your training data has the missingness patterns you expect in production.
The indicator is also fitted, so its set of columns is learned from the training data only. The same leakage rule from the previous chapters applies.
The indicator matters most with a simple fill
Indicators work well with a fill value that sits inside the normal range of the data. The model sees an ordinary-looking number plus a flag saying it is fake.
This helps linear models in particular. Mean imputation puts missing rows at the center of the feature, which makes the effect of missingness hard to separate from a normal value. The indicator column gives the model a separate coefficient for it. Tree-based models can often learn the same thing from a sentinel constant, but an explicit indicator is clearer and works with any estimator.
Using indicators in a pipeline
Inside a ColumnTransformer, each imputer adds its own indicators next to its own output columns.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
df = pd.DataFrame({
"age": [25, np.nan, 40, 31, 52, np.nan],
"income": [40000, 52000, np.nan, 61000, 75000, 48000],
})
y = [0, 1, 0, 1, 1, 0]
model = Pipeline([
("prep", ColumnTransformer([
("num", Pipeline([
("impute", SimpleImputer(strategy="median", add_indicator=True)),
("scale", StandardScaler()),
]), ["age", "income"]),
])),
("clf", LogisticRegression()),
])
model.fit(df, y)
print(model.named_steps["prep"].get_feature_names_out())The scaler also scales the indicator columns, which is harmless for most models. If you prefer unscaled 0/1 flags, place the indicator in its own branch with MissingIndicator, a transformer in sklearn.impute that produces only the flags.
Deciding when to use it
| Situation | Use indicators? |
|---|---|
| Missingness likely relates to the target | Yes |
| Few missing values (under about 1%) | Usually not worth the extra columns |
| Many sparse columns and a small dataset | Careful, extra columns can overfit |
| Missing completely at random | No gain, may add noise |
You can test it empirically. Run cross-validation with and without add_indicator and compare scores.
Exercise
Exercise
You fit SimpleImputer(strategy="mean", add_indicator=True) on a training matrix with 5 columns. Only columns 1 and 3 contain NaN. How many columns does transform return, and which columns are the indicators?
Show answer
It returns 7 columns. The first 5 are the imputed features. The last 2 are indicators, one for column 1 and one for column 3, because only those columns had missing values during fit.
Exercise
A teammate fits the imputer on the full dataset with add_indicator=True before splitting into train and test sets. What problem does this cause, and what is the fix?
Show answer
The statistics and the set of indicator columns are learned using test data, which leaks information into preprocessing. Put the imputer in a Pipeline and fit it on the training split only, or use cross-validation on the whole pipeline.