SimpleImputer缺失指示审查:add_indicator为何漏记测试时首次缺失
配图由AI模型生成,为概念示意图,示意格子与标记不代表下面的实测矩阵或软件截图。
AI生成预处理代码时,常把SimpleImputer(add_indicator=True)解释为“填补数值,同时告诉模型哪些输入缺失”。这句话少了一个限制:追加哪些指示列,由训练阶段决定。测试时某个原本完整的特征首次缺失,数值可以被填好,缺失身份却未必保留下来。
训练时固定的是指示列名单
本文锁定scikit-learn 1.8.0,使用稠密数值矩阵、np.nan和均值填补,训练中没有整列全空的特征。SimpleImputer官方文档明确说明:训练时没有缺失的特征,不会因为测试时出现缺失就获得指示列。
可以把拟合分成两件事:计算每列填补统计量;记录至少出现过一次缺失的列索引。transform用训练统计量填补,再按照已经记录的索引追加缺失标记。当前批次有更多缺失,不会让这份名单自动增长。indicator_.features_与get_feature_names_out可以核对实际输出含义。
两个不同输入,变成同一个向量
下面有a、b、c三列,训练均值为[20,2,200],只有b出现过缺失,所以输出只有四列:三个填补后的值,加上b的缺失指示。
测试第一行的a缺失,第二行的a确实观测到20;其他值相同。两行转换后都是[20,2,200,0]。这是表示层面的信息合并:只接收该向量的确定性预测函数无法再区分这两种输入。不能靠“数值等于均值”反推缺失,因为真实观测也可能恰好等于均值。
完整可运行实验
代码同时检查输出列名、新缺失不会扩列、逆变换的边界,以及保留全部缺失标记的并行方案。保存为test.py,按首行安装固定版本后运行。
# python -m pip install numpy==2.3.5 scikit-learn==1.8.0
import warnings
import numpy as np
import sklearn
from numpy.testing import assert_array_equal, assert_allclose
from sklearn.impute import MissingIndicator, SimpleImputer
from sklearn.pipeline import FeatureUnion
assert sklearn.__version__ == "1.8.0", sklearn.__version__
names = ["a", "b", "c"]
train = np.array([
[10.0, 1.0, 100.0],
[20.0, np.nan, 200.0],
[30.0, 3.0, 300.0],
])
test = np.array([
[np.nan, 2.0, 200.0], # a: newly missing
[20.0, 2.0, 200.0], # fully observed control
[20.0, np.nan, 200.0], # b: missing during fit too
[20.0, 2.0, np.nan], # c: newly missing
])
assert not np.isnan(train).all(axis=0).any()
imp = SimpleImputer(strategy="mean", add_indicator=True)
train_out = imp.fit_transform(train)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
test_out = imp.transform(test)
assert not caught
assert_allclose(imp.statistics_, [20.0, 2.0, 200.0])
assert_array_equal(imp.indicator_.features_, [1])
assert imp.indicator_.error_on_new is False
assert train_out.shape == (3, 4) and test_out.shape == (4, 4)
assert_allclose(test_out[:, :3], np.tile([20.0, 2.0, 200.0], (4, 1)))
assert_array_equal(test_out[:, 3], [0.0, 0.0, 1.0, 0.0])
assert_array_equal(test_out[0], test_out[1])
assert_array_equal(test_out[3], test_out[1])
assert_array_equal(
imp.get_feature_names_out(names), ["a", "b", "c", "missingindicator_b"]
)
restored = imp.inverse_transform(test_out)
assert_array_equal(np.isnan(restored), [
[False, False, False], [False, False, False],
[False, True, False], [False, False, False],
])
# A standalone MissingIndicator has a different default for error_on_new.
strict = MissingIndicator(sparse=False).fit(train)
try:
strict.transform(test)
except ValueError as exc:
assert "missing values in transform but have no missing values in fit" in str(exc)
else:
raise AssertionError("Expected an error for newly missing features")
loose = MissingIndicator(error_on_new=False, sparse=False).fit(train)
assert_array_equal(loose.transform(test), np.isnan(test[:, [1]]))
assert_array_equal(loose.features_, [1])
# Both branches receive the original, unfilled matrix.
full = FeatureUnion([
("values", SimpleImputer(strategy="mean", copy=True)),
("missing", MissingIndicator(features="all", sparse=False)),
])
full_train = full.fit_transform(train)
full_test = full.transform(test)
assert full_train.shape == (3, 6) and full_test.shape == (4, 6)
assert_allclose(full_test[:, :3], test_out[:, :3])
assert_array_equal(full_test[:, 3:], np.isnan(test).astype(float))
assert_array_equal(full_train[:, [3, 5]], np.zeros((3, 2)))
assert not np.array_equal(full_test[0], full_test[1])
assert not np.array_equal(full_test[3], full_test[1])
# When fit saw no missing entries, add_indicator adds zero columns.
clean_train = np.array([[10.0, 1.0, 100.0], [30.0, 3.0, 300.0]])
clean = SimpleImputer(add_indicator=True).fit(clean_train)
assert clean.indicator_.features_.size == 0
assert clean.transform(test).shape == (4, 3)
try:
imp.transform(test[:, :2])
except ValueError as exc:
assert "expecting 3 features" in str(exc)
else:
raise AssertionError("Changing the input column count must fail")
print(f"NumPy={np.__version__}, scikit-learn={sklearn.__version__}")
print("statistics=", imp.statistics_.tolist())
print("indicator_features=", imp.indicator_.features_.tolist())
print("output_names=", imp.get_feature_names_out(names).tolist())
print("add_indicator_output=", test_out.tolist())
print("new_missing_row_equals_observed_control=", bool(np.array_equal(test_out[0], test_out[1])))
print("standalone_default_rejects_new_missing=", True)
print("all_indicator_output=", full_test.tolist())
print("Fit-time schema, new missingness, inverse and parallel-branch checks: PASS")实际运行结果
NumPy=2.3.5, scikit-learn=1.8.0 statistics= [20.0, 2.0, 200.0] indicator_features= [1] output_names= ['a', 'b', 'c', 'missingindicator_b'] add_indicator_output= [[20.0, 2.0, 200.0, 0.0], [20.0, 2.0, 200.0, 0.0], [20.0, 2.0, 200.0, 1.0], [20.0, 2.0, 200.0, 0.0]] new_missing_row_equals_observed_control= True standalone_default_rejects_new_missing= True all_indicator_output= [[20.0, 2.0, 200.0, 1.0, 0.0, 0.0], [20.0, 2.0, 200.0, 0.0, 0.0, 0.0], [20.0, 2.0, 200.0, 0.0, 1.0, 0.0], [20.0, 2.0, 200.0, 0.0, 0.0, 1.0]] Fit-time schema, new missingness, inverse and parallel-branch checks: PASS
b缺失的第三行得到标记1;a或c首次缺失的行没有对应标记。inverse_transform也只能利用已有指示列恢复缺失位置,本例会恢复b的np.nan,却无法恢复a和c的原始缺失。
别混淆独立指示器的默认行为
1.8.0版本源码显示,填补器内部建立指示器时使用error_on_new=False。独立的MissingIndicator默认却是True,本例会因为a和c新出现缺失而报错。将它改为False,只是允许这类输入通过,不会增加指示列。
需要全部标记时,提前建立完整结构
实验用FeatureUnion并行运行填补器和features="all"的指示器,两者都读取原始矩阵,再拼接结果。于是三个值后面始终跟着a、b、c的三个缺失标记。保留copy=True,避免填补分支原地修改输入;也不要串行地先填好数值再提取标记,否则原始缺失位置已经消失。官方用户指南给出了这种组合方向。
完整指示结构不等于模型已经学会应对新缺失。a和c的标记在训练中一直为0,下游模型并没有见过它们为1时的训练证据。是否需要缺失压力测试、数据质量告警或新的训练样本,应另行验证,不能仅凭列数变多宣称泛化更好。
代码审查时还要守住两条边界
这里的“新缺失”指已有特征首次出现空值,不是允许测试矩阵新增或减少输入列。若训练完全没有缺失,add_indicator甚至不会追加任何列,代码也验证了这两个边界。
不要为了让指示列齐全而把测试集拼进训练集重新fit。填补统计量和指示列名单都应只从对应训练数据获得;交叉验证时,让整套预处理随每个训练折拟合。审查重点是保存了哪些信息、在何时确定列结构,而不只是检查结果里还有没有np.nan。


