Sub topic 2
Your first SimpleImputer: fit, transform and statistics_
This chapter assumes you can read basic Python and NumPy arrays, know the scikit-learn estimator pattern (fit, transform, predict), and understand the difference between training and test data. You will fit a SimpleImputer, read what it learned, and see how it fills a matrix.
What SimpleImputer does
SimpleImputer is a scikit-learn transformer that replaces missing entries in a feature matrix. In a NumPy float array, a missing entry is stored as np.nan. By default the imputer treats every NaN as missing.
It works column by column. For each column it computes one fill value, either a statistic of the observed values or a constant you choose. It then writes that value wherever the column has a gap.
Fit, then transform
Like other scikit-learn transformers, SimpleImputer splits the work into two steps:
fit(X)scans each column, ignores theNaNentries, and computes the fill value.transform(X)returns a copy of the matrix with eachNaNreplaced by the fill value for its column.
fit_transform(X) runs both steps in one call. Here it is on a small matrix with two gaps:
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="mean")
X_filled = imputer.fit_transform(X)
print(imputer.statistics_) # [4. 2.5]
print(X_filled)
# [[1. 2. ]
# [4. 3. ]
# [7. 2.5]]The first column holds 1 and 7 once the NaN is ignored, so its mean is 4. The second column holds 2 and 3, so its mean is 2.5. Those are the numbers the imputer used.
Reading statistics_
After fit, the imputer stores its learned fill values in the statistics_ attribute. This is a 1-D array with one entry per column, in column order. A trailing underscore marks an attribute that exists only after fitting.
Check statistics_ whenever imputation matters to your results. It shows exactly what the model will insert, and you can compare it to your own calculation. In the example above, [4. 2.5] matches the hand-computed means.
Why the two steps are separate
You might wonder why scikit-learn does not just fill the matrix in one step. The split exists so the fill values can be learned from one dataset and applied to another. That matters when you have training data and test data.
The example below learns the median from the training set only, then applies it to the test set:
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) # learns the median of the training data only
print(imputer.statistics_) # [2.]
print(imputer.transform(X_test))
# [[2.]
# [5.]]Three things happen here:
- The training column has the observed values 1, 2 and 100. Their median is 2.
- The test matrix is never used to compute the fill value. Its
NaNbecomes 2, the training median. - The median is not pulled upward by the outlier 100. A mean would have been about 34.3.
Learning from training data alone keeps information from the test set out of preprocessing. A later chapter covers this leakage problem in detail. For now, remember the pattern: fit on training data, transform on everything.
How the pieces connect
The statistics_ array is the only thing carried from fit to transform. The imputer remembers nothing else about the training rows.
Common errors
- Expecting the input to change.
transformreturns a new array by default. The originalXkeeps itsNaNvalues, so assign the result to a variable. - Fitting on the wrong data. Calling
fit_transformseparately on the training set and on the test set computes two different sets of fill values. Fit once on training data, then calltransformon the test set. - Reading statistics_ before fitting. It does not exist yet and raises an
AttributeError. - Passing a column that is entirely
NaN. The imputer has no observed value to compute a statistic from. A later chapter covers how it handles this.
Key points
SimpleImputerreplaces missing entries column by column with one fill value per column.fitlearns the fill values and stores them instatistics_.transformapplies them.- The default
strategyis"mean". The median resists outliers. - Learn fill values from training data only, then reuse them on new data.
The next chapter compares the four strategies and how to choose among them.
Exercise
You run imputer = SimpleImputer(strategy="mean") and imputer.fit(np.array([[2.0, np.nan], [4.0, 6.0], [np.nan, 10.0]])). What does imputer.statistics_ contain, and what does imputer.transform(np.array([[np.nan, np.nan]])) return?
Show answer
statistics_ is [3. 8.]. Column 0 has observed values 2 and 4, with mean 3. Column 1 has observed values 6 and 10, with mean 8. Transforming the row [nan, nan] returns [[3. 8.]], because each NaN is replaced by the fill value learned for its column.