TExcelTAD

Missing-Value Indicators

Imputation replaces an unknown value with a guess, and in doing so it erases a fact: that the value was unknown. Often that fact is informative. Applicants in financial difficulty skip the income question more often; a lab test is missing because the doctor saw no reason to order it; a sensor goes silent when the machine is switched off. Missing-Value Analysis showed how to detect such patterns. This lesson is method 6 of the eight: keep the fact as a feature.

The idea

For every column that has missing values (in the training data), add a 0/1 column:

income income (imputed) income_missing
42,000 42,000 0
NaN 38,950 1
55,500 55,500 0

The model now sees two things: a plausible number where the value is unknown, and a flag that tells it not to trust that number and to use whatever "being missing" says about the target. Linear models get a separate coefficient for the flag; trees can split on it.

From scratch

python · try it yourself
import numpy as np

X_train = np.array([[42000, 31], [np.nan, 45], [55500, np.nan], [61000, 52], [np.nan, 38]])
X_test = np.array([[np.nan, 29], [48000, 41]])

class ImputeWithIndicator:
    def fit(self, X):
        self.medians_ = np.nanmedian(X, axis=0)
        self.flag_cols_ = np.where(np.isnan(X).any(axis=0))[0]   # decided on training data
        return self
    def transform(self, X):
        miss = np.isnan(X)
        filled = np.where(miss, self.medians_, X)
        return np.hstack([filled, miss[:, self.flag_cols_].astype(float)])

t = ImputeWithIndicator().fit(X_train)
print("medians:", t.medians_.tolist(), " flag columns:", t.flag_cols_.tolist())
print(t.transform(X_test).tolist())
medians: [55500.0, 41.5]  flag columns: [0, 1]
[[55500.0, 29.0, 1.0, 0.0], [48000.0, 41.0, 0.0, 0.0]]

Two details matter. The set of indicator columns is decided on the training data, so the output always has the same number of columns, even if a test batch happens to have no missing values (or has them in a column that never had any in training). And the fill values are the training medians, as in the previous lesson.

In scikit-learn

Either add the flags with the imputer, SimpleImputer(add_indicator=True) (also available on KNNImputer and IterativeImputer), or use MissingIndicator on its own, for example in a FeatureUnion. The flags follow the imputed columns in the output.

python · try it yourself
import numpy as np
from sklearn.impute import MissingIndicator, SimpleImputer

X_train = np.array([[42000, 31], [np.nan, 45], [55500, np.nan], [61000, 52], [np.nan, 38]])
imp = SimpleImputer(strategy="median", add_indicator=True).fit(X_train)
print(imp.get_feature_names_out(["income", "age"]).tolist())
print(imp.transform(np.array([[np.nan, 29.0], [48000, np.nan]])).tolist())
print(MissingIndicator(features="all").fit_transform(X_train).astype(int).tolist())
['income', 'age', 'missingindicator_income', 'missingindicator_age']
[[55500.0, 29.0, 1.0, 0.0], [48000.0, 41.5, 0.0, 1.0]]
[[0, 0], [1, 0], [0, 1], [0, 0], [1, 0]]

features="missing-only" (the default) creates flags only for columns that had missing values during fit; features="all" creates one per column.

When the indicator pays off

Here is a credit dataset where applicants with high risk skip the income field more often. We compare median imputation with and without the indicator, measured with 5-fold cross-validation on 3,000 applicants:

python · try it yourself
import numpy as np
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
from sklearn.preprocessing import StandardScaler

rng = np.random.default_rng(0)
n = 3000
risk = rng.random(n)
income = rng.normal(50, 12, n) - 20 * risk            # in thousands
debt = rng.normal(0.4, 0.15, n) + 0.3 * risk
default = (rng.random(n) < 0.05 + 0.4 * risk).astype(int)
X = np.column_stack([income, debt])

def score(X, indicator):
    pipe = make_pipeline(SimpleImputer(strategy="median", add_indicator=indicator),
                         StandardScaler(), LogisticRegression())
    return cross_val_score(pipe, X, default, cv=5, scoring="roc_auc").mean()

for mechanism in ["MCAR", "depends on the label"]:
    Xm = X.copy()
    p = np.full(n, 0.2) if mechanism == "MCAR" else 0.05 + 0.5 * default
    Xm[rng.random(n) < p, 0] = np.nan
    print(f"{mechanism:22s} missing {np.isnan(Xm[:, 0]).mean():.2f}  "
          f"AUC without flag {score(Xm, False):.3f}  with flag {score(Xm, True):.3f}")
MCAR                   missing 0.19  AUC without flag 0.602  with flag 0.603
depends on the label   missing 0.18  AUC without flag 0.600  with flag 0.802

When income is missing completely at random, the flag carries no information and the two scores are within noise (0.602 vs 0.603). When missingness depends on default, the flag alone is a strong predictor and the AUC jumps from 0.600 to 0.802. The flag costs one column per incomplete feature, so adding it is a cheap default.

Note: Models that handle missing values natively learn the same thing without a flag. HistGradientBoostingClassifier (and XGBoost, LightGBM) send missing values down whichever branch of each split works best, so for them imputation is optional. Linear models, kNN, SVMs and neural networks need imputation and benefit from the flag.

Is a predictive flag a good thing?

A flag that predicts the label is useful only if the same missingness pattern will exist when the model is used. Two warnings:

  • Process artefacts. If a field became mandatory last month, new data will never be missing and the flag stops working. If missingness comes from how the training data was collected (labels filled in after the outcome, records completed only for defaulters), the flag is leakage: it encodes the outcome. Ask how the value becomes missing in production.
  • Fairness. Missingness can be tied to a group (a clinic, a language, an age band). A flag can then act as a proxy for that group; check performance per group (Responsible ML).

Pitfalls

  • Deciding the flag columns on all data: a column with missing values only in the test set gets a flag that the model never saw during training. Fit the indicator on training data.
  • Flags for every column out of habit when the data has no missing values in training: features="missing-only" creates none, which is right.
  • Dropping the flag after imputing "because the column is full now": the information is gone the moment you drop it.

Practice

  1. A hospital model uses lactate, which is measured only when a doctor suspects sepsis. Should you add lactate_missing? What could go wrong?
Answer

The flag will be highly predictive, because "not measured" means "doctor not worried". That is genuine information if the model is used at the same point in care where doctors have already decided what to measure. It goes wrong if the model is meant to screen patients before a doctor has looked at them (the flag then encodes the doctor's judgement the model is supposed to replace), or if ordering habits change.

  1. After SimpleImputer(add_indicator=True) on columns [a, b, c], where only b had missing values during fit, how many output columns are there?
Answer

Four: a, b, c imputed, plus missingindicator_b.

Test yourself

What information does a missing-value indicator keep that imputation alone erases?

  1. The original value
  2. The fact that the value was unknown
  3. The column's mean
  4. The row order

Income is missing completely at random (MCAR). What do you expect from adding an indicator?

  1. A large gain
  2. About the same score, because the flag is unrelated to the label
  3. A crash
  4. Leakage

Which model can use missing values directly, without imputation?

  1. LogisticRegression
  2. KNeighborsClassifier
  3. HistGradientBoostingClassifier
  4. SVC

A field was optional in the training data but becomes mandatory next month. What happens to a model relying on its missing flag?

  1. Nothing
  2. The flag is always 0 in new data, so the pattern it learned no longer applies
  3. It improves
  4. It throws an error