Sub topic 2
Telling the Imputer What Counts as Missing
Assume you know basic NumPy, pandas, and the scikit-learn fit/transform pattern. This chapter covers sentinel values, categorical data, and training-data leakage.
Missing Values and Sentinel Values
SimpleImputer treats np.nan as missing by default. Some datasets use another marker, such as -1, "?", or "unknown". A sentinel value is a special value that represents missing data.
Set the missing_values parameter to match the marker in your feature matrix:
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([
[1, -1],
[-1, 4],
[3, 6],
])
imputer = SimpleImputer(
missing_values=-1,
strategy="constant",
fill_value=0,
)
print(imputer.fit_transform(X))
# [[1 0]
# [0 4]
# [3 6]]The marker must match the data exactly. If an empty string means missing, use missing_values="". Do not use a legitimate value as a sentinel, or the imputer will replace valid observations.
Categorical Columns and `fill_value`
Categorical data contains labels such as "Oslo" or "Rome", rather than measurements. For these columns, use most_frequent to copy the most common category, or constant to create an explicit category such as "Unknown".
With strategy="constant", fill_value specifies the replacement:
import numpy as np
from sklearn.impute import SimpleImputer
cities = np.array(["Oslo", "?", "Rome", "Oslo"], dtype=object)
imputer = SimpleImputer(
missing_values="?",
strategy="constant",
fill_value="Unknown",
)
print(imputer.fit_transform(cities.reshape(-1, 1)).ravel())
# ['Oslo' 'Unknown' 'Rome' 'Oslo']An explicit category preserves the fact that the original value was unavailable. This can be more informative than assigning the most common category.
Fit on Training Data Only
fit learns the replacement value. transform applies it. Fit on training data, then reuse that fitted imputer for validation, test, and future data:
import numpy as np
from sklearn.impute import SimpleImputer
X_train = np.array([[1.0], [2.0], [np.nan], [100.0]])
X_test = np.array([[np.nan], [5.0]])
imputer = SimpleImputer(strategy="median")
imputer.fit(X_train)
print(imputer.statistics_) # [2.]
print(imputer.transform(X_test)) # [[2.], [5.]]Using test data during fit causes data leakage: information from evaluation data influences preprocessing and can make performance look better than it really is.
Exercise
Which parameter should you set when -1 represents missing numeric values, and which parameter chooses the replacement category?
Show answer
Set missing_values=-1 and use fill_value with strategy="constant" to choose the replacement category or value.