
Filling Missing Values with the Mean Isn't Neutral
- كاتب موثّق
- scikit-learn 1.9
محتويات المقال
df.fillna(df.mean()), train a linear regression and get an of 0.488. Predictions for their best customers come out consistently too low. Nobody suspects the one-line imputation, because the mean is the most neutral number there is. Except it isn't neutral: in this data, the customers who skip the income question are mostly the ones who earn the most.
The common misconception
The mean is the best single guess when you know nothing else, and filling with it leaves the column's average unchanged. It's the default. SimpleImputerusesstrategy="mean"unless told otherwise, and pandas makes it one line.With a handful of gaps scattered at random, it really does little harm. Dropping incomplete rows feels worse: it throws away whole customers, so filling looks like the conservative choice.
What actually happens
The same guess for every gap
SimpleImputer is univariate: it looks only at the column being filled, so every missing row gets exactly the same number. Those rows sit at the mean, adding nothing to the column's spread while counting toward its size, so the variance shrinks. They also carry no link to the target or to other columns, which dilutes the relationships the model is supposed to learn. Switching to the median doesn't change this: it's a different number, but still one number for every gap. Google's Machine Learning Crash Course puts it simply: imputed values are rarely as good as the actual values.
The mean of the answers isn't the mean of the gaps
import numpy as npimport pandas as pdfrom sklearn.impute import SimpleImputerfrom sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import KFold, cross_val_scorefrom sklearn.pipeline import make_pipelinerng = np.random.default_rng(0)income = rng.normal(50, 15, 2000) # yearly income, thousandsage = rng.uniform(20, 65, 2000)spend = 2 * income + 0.5 * age + rng.normal(0, 10, 2000)skip = (income > 60) & (rng.random(2000) < 0.8) # high earners skip itX = pd.DataFrame({"income": np.where(skip, np.nan, income), "age": age})fill, real = X["income"].mean(), income[skip].mean()print(f"imputed {fill:.1f}, skipped rows really average {real:.1f}")model = make_pipeline(SimpleImputer(strategy="mean"), LinearRegression())cv = KFold(n_splits=5, shuffle=True, random_state=0)print(f"R^2 {cross_val_score(model, X, spend, cv=cv).mean():.3f}")# imputed 44.6, skipped rows really average 68.7# R^2 0.488import numpy as npimport pandas as pdfrom sklearn.ensemble import HistGradientBoostingRegressorfrom sklearn.impute import SimpleImputerfrom sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import KFold, cross_val_scorefrom sklearn.pipeline import make_pipelinerng = np.random.default_rng(0)income = rng.normal(50, 15, 2000) # yearly income, thousandsage = rng.uniform(20, 65, 2000)spend = 2 * income + 0.5 * age + rng.normal(0, 10, 2000)skip = (income > 60) & (rng.random(2000) < 0.8) # high earners skip itX = pd.DataFrame({"income": np.where(skip, np.nan, income), "age": age})flagged = make_pipeline(SimpleImputer(add_indicator=True), LinearRegression())boosting = HistGradientBoostingRegressor(random_state=0) # NaN-aware splitscv = KFold(n_splits=5, shuffle=True, random_state=0)for name, model in [("mean + indicator", flagged), ("boosting, NaN kept", boosting)]: score = cross_val_score(model, X, spend, cv=cv).mean() print(f"{name:<18} R^2 {score:.3f}")# mean + indicator R^2 0.867# boosting, NaN kept R^2 0.847The gap is a feature
add_indicator=True, SimpleImputer appends a 0/1 column for every feature that had missing values during training, the output of scikit-learn's MissingIndicator. The linear model learns one more weight, for "income was skipped", which in this data means "probably earns a lot". R² climbs to 0.867.
temperature_is_imputed. scikit-learn's own imputation example adds the indicator to every strategy it compares.
Or let the model see the gap
HistGradientBoostingRegressor and HistGradientBoostingClassifier accept NaN directly. At each split, the tree learns whether rows with a missing value should go left or right, based on which gives the better gain, and when missingness is predictive it can split on "missing or not" itself. With no imputer at all, it scores 0.847 here.
add_indicator=True | ||
IterativeImputer, KNNImputer | IterativeImputer is still experimental | |
HistGradientBoosting models |
How to apply it in your project
Measure the gaps Count missing values per column, and compare the target for rows with and without each value. Ask why the value is missing An optional field, a sensor that was down, or an event that never happened? "Never ordered" isn't an average order date; it deserves its own signal. Keep the signal Use add_indicator=Truefor linear, distance-based and neural models, or a model with native NaN support such asHistGradientBoosting.Choose the fill deliberately Median for skewed columns with outliers, a multivariate imputer when other columns can predict the missing one. Compare inside a pipeline Cross-validate dropping, mean fill, fill plus indicator, and native NaN handling, with the imputer inside the pipeline so each fold fits it on training rows only.
Key takeaways
Mean imputation gives every gap the same value: the spread shrinks, and the fact that a value was missing is lost. When missingness depends on the value, the mean of the answers is wrong for the gaps: 44.6 against 68.7 here. A missing indicator turns the gap into a feature; in the example, R² rose from 0.488 to 0.867. Fit imputers on training data inside a pipeline, and ship them with the model.
📚 المصادر
Imputation of missing values — scikit-learn User Guide Imputing missing values before building an estimator — scikit-learn examples Data characteristics — Google Machine Learning Crash Course Histogram-Based Gradient Boosting: Missing values support — scikit-learn User Guide Common pitfalls and recommended practices — scikit-learn User Guide
التعليقات (0)