Sub topic 2
Your first SimpleImputer: fit, transform and statistics_
This chapter assumes you know basic Python and NumPy arrays, can read a pandas DataFrame, and have used the scikit-learn estimator pattern (fit, transform, predict). It also assumes you know why training data and test data are kept apart. The previous chapter explained why missing values need handling. This chapter takes the smallest working imputer apart so you know what it learns, where it stores that knowledge, and what it does when you call it.
What SimpleImputer is
SimpleImputer is a scikit-learn transformer. A transformer is an object that learns something from data with fit and then changes data with transform. SimpleImputer lives in sklearn.impute. For each column of a feature matrix, it computes one replacement value, and it writes that value into every cell of the column that is marked as missing.
The word "simple" refers to the replacement rule. Each column is handled on its own, and each missing cell gets the same value as the other missing cells in that column. The imputer does not look at other columns, and it does not use the target y.
The first example
Here is a small matrix with two missing entries.
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 call to fit_transform did two things:
- It computed the mean of each column while ignoring
NaN. Column 0 holds 1.0 and 7.0, so its mean is 4.0. Column 1 holds 2.0 and 3.0, so its mean is 2.5. - It replaced each
NaNwith the mean of its own column.
You can confirm the first step with plain NumPy. np.nanmean(X, axis=0) returns [4. 2.5], the same numbers.
Notice that the original X is unchanged. By default SimpleImputer works on a copy (copy=True), so you get a new array back.
Fit and transform are separate steps
fit_transform is a shortcut for fit followed by transform on the same data. The two steps do different jobs, and keeping them apart is the point of the estimator pattern.
| Step | Input | What happens | What changes |
|---|---|---|---|
| `fit(X)` | Data to learn from | Computes one replacement value per column, ignoring missing entries | The imputer stores the values in `statistics_` |
| `transform(X)` | Any data with the same columns | Replaces each missing entry with the stored value for its column | Nothing in the imputer. A filled copy of `X` is returned |
The diagram shows how data and learned values move.
Because the two steps are separate, you can learn from one dataset and fill another one:
import numpy as np
from sklearn.impute import SimpleImputer
X_train = np.array([[1.0, 2.0],
[np.nan, 3.0],
[7.0, np.nan]])
imputer = SimpleImputer(strategy="mean")
imputer.fit(X_train)
print(imputer.statistics_) # [4. 2.5]
X_new = np.array([[np.nan, 5.0],
[2.0, np.nan]])
print(imputer.transform(X_new))
# [[4. 5. ]
# [2. 2.5]]
print(imputer.statistics_) # [4. 2.5]The new rows contain different numbers than the training rows, but the filled values are still 4.0 and 2.5. transform uses what fit learned. It does not recompute anything from X_new, and the last print shows that statistics_ did not move. Why this matters for evaluating a model is the subject of a later chapter. For now, remember the rule: fit learns, transform applies.
If you call fit a second time, the imputer forgets the old values and learns new ones from the new data.
Reading statistics_
After fit, the attribute statistics_ holds the fill value for each column. It is a NumPy array with one entry per feature, in column order. In scikit-learn, attributes whose names end in an underscore are the ones created by fit. Before fit they do not exist, and reading them raises an AttributeError.
statistics_ is useful for three reasons:
- Checking. You can compare it with your own calculation, such as
np.nanmean, to be sure the imputer does what you expect. - Reporting. You can log or save the exact values used to fill a dataset.
- Debugging. If a model behaves oddly after imputation, an unexpected fill value (for example one pulled far off by outliers) is often the cause.
The same attribute is used by every strategy. With strategy="median" it holds medians. With strategy="most_frequent" it holds the most common value of each column. With strategy="constant" it holds the constant you chose. The next chapter compares these strategies in detail. This is a short example with the median, so you can see the attribute change meaning:
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.]]The observed training values are 1, 2 and 100, so the median is 2. A mean would have been 34.33, pulled up by the outlier. The test row that was missing now holds 2.0, and the test value 5.0 is untouched. Only missing entries are ever changed. Observed values pass through exactly as they were.
What the imputer expects as input
SimpleImputer follows the same input rules as most scikit-learn estimators. Several of them affect how you use statistics_ and transform.
Same columns, same order
transform matches columns by position, not by name. If you fit on two columns and transform an array with three, scikit-learn raises a ValueError saying the number of features does not match. If you fit on [age, income] and later pass [income, age], no error is raised, and the age fill value is applied to the income column. With NumPy arrays you must keep the column order yourself. DataFrames give you more protection, as the next section shows.
Input must be two-dimensional
A feature matrix has shape (n_samples, n_features). A single column therefore needs shape (n, 1), as in the median example above, where each row is written as [x]. A flat array of shape (n,) raises a ValueError asking you to reshape it. Use x.reshape(-1, 1) for a single feature.
Numbers by default, text with some strategies
The mean and median strategies need numeric columns. The most_frequent and constant strategies also work on string columns. That is covered in a later chapter on categorical columns.
Infinite values are not missing
np.inf is not treated as missing, and the imputer does not accept it in the input. If your data can contain infinities, convert them to NaN first, for example with np.where(np.isinf(X), np.nan, X).
Working with DataFrames
You can pass a pandas DataFrame directly. The imputer records the column names it saw during fit in feature_names_in_. On later calls, scikit-learn compares the names in the data with the names it saw during fit. If they differ, it raises an error or a warning, depending on the version. That check catches the column-order mistake described above.
By default transform returns a NumPy array, even when you pass a DataFrame, so the column names and index are lost. Call set_output(transform="pandas") to get a DataFrame back. This method exists in scikit-learn 1.2 and later.
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
df = pd.DataFrame({"a": [1.0, np.nan, 7.0],
"b": [2.0, 3.0, np.nan]})
imputer = SimpleImputer(strategy="mean").set_output(transform="pandas")
out = imputer.fit_transform(df)
print(imputer.feature_names_in_) # ['a' 'b']
print(out)
# a b
# 0 1.0 2.0
# 1 4.0 3.0
# 2 7.0 2.5Note that statistics_ is still a plain array with no names. Match it to columns by position, or build a labeled view with pd.Series(imputer.statistics_, index=imputer.feature_names_in_).
Common errors at this stage
These are the mistakes people make most often with a first imputer:
- Calling
transformbeforefit. The imputer has nothing to apply, so scikit-learn raisesNotFittedError. Callfitorfit_transformfirst. - Using
fit_transformon test data. This fits a new imputer on the test set and learns its statistics instead of reusing the training ones. Usetransformfor any data that was not part offit. - Expecting the input to change.
SimpleImputerreturns a new array. If you ignore the return value, nothing has been filled. Keep the result, as inX_filled = imputer.transform(X). - Passing a 1D array. Reshape it to
(n, 1). - Assuming column names survive. Without
set_output(transform="pandas")the result is a bare array. - Mixing up column order. With NumPy input,
transformtrusts position. Keep the same layout in training and later data. - Using a numeric strategy on text.
meanandmedianfail on string columns. Pickmost_frequentorconstant, or impute those columns in a separate step.
A note on columns that are entirely missing
If a column has no observed values in the data given to fit, there is nothing to average. By default, SimpleImputer drops such a column from its output, so the result has fewer columns than the input. The statistics_ value for that column is NaN. A later chapter covers this and the keep_empty_features option. For now, if the number of output columns is smaller than you expected, check for an all-missing column.
Exercise
You fit SimpleImputer(strategy="mean") on X_train, then call imputer.transform(X_test). Does imputer.statistics_ change, and which data are the filled values based on?
Show answer
No, statistics_ does not change. transform only reads the stored values. The filled values come from the mean of each column in X_train, computed with missing entries ignored during fit. The test data affects only which cells are filled, never the values used to fill them.
Exercise
Given X = np.array([[2.0, np.nan], [np.nan, 8.0], [6.0, 4.0]]), what does SimpleImputer(strategy="mean").fit(X).statistics_ return, and what is the filled matrix?
Show answer
statistics_ is [4. 6.]. Column 0 has observed values 2.0 and 6.0 with mean 4.0. Column 1 has observed values 8.0 and 4.0 with mean 6.0. The filled matrix is [[2. 6.], [4. 8.], [6. 4.]].
Exercise
A teammate writes X_test_filled = SimpleImputer(strategy="median").fit_transform(X_test) after already fitting an imputer on X_train. What is wrong with this line, and how would you fix it?
Show answer
It creates a new imputer and fits it on the test data, so the fill values come from the test set instead of the training set. Reuse the imputer fitted on X_train, and call only transform: X_test_filled = imputer.transform(X_test).
Exercise
You fit an imputer on a NumPy array with columns [age, income]. Later you pass an array with the columns in the order [income, age] to transform. Does scikit-learn raise an error, and what goes wrong?
Show answer
No error is raised, because the shapes match and NumPy arrays carry no names. transform matches columns by position, so the age fill value is written into the income column and the income fill value into the age column. Keeping the column order identical, or passing DataFrames so that feature_names_in_ can be checked, prevents this.