我已经定义了适合一个分类特征“性别”的数据:
data = pd.DataFrame({
'age': [25,19, 17],
'sex': ['female', 'male', 'female'],
'won_lottery': [False, True, False]
})
X = data[['age', 'sex']]
y = data['won_lottery']
和转换分类特征的管道:
ohe = OneHotEncoder(handle_unknown='ignore')
cat_transformers = Pipeline([
('onehot', ohe)
])
直接用数据拟合cat_transformers
时
cat_transformers.fit(X[['sex']], y)
print(ohe.get_feature_names())
我能够获取由 OneHotEncoder
实例创建的输出特征的名称:
['x0_female' 'x0_male']
但是,如果我将 cat_transformers
封装到 ColumnTransformer
中:
preprocessor = ColumnTransformer(
transformers=[
('cat', cat_transformers, ['sex'])
]
)
preprocessor.fit(X, y)
print(ohe.get_feature_names())
它失败了
sklearn.exceptions.NotFittedError: This OneHotEncoder instance is not fitted yet.
Call 'fit' with appropriate arguments before using this method.
我希望在 ColumnTransformer
上调用 fit()
会导致在其所有转换器上调用 fit()
。
为什么这样不行?
最佳答案
好的,我现在明白了。我正在安装 OneHotEncoder
的一个实例并在另一个实例上检查功能:
print(id(ohe))
print(id(preprocessor.named_transformers_['cat'].named_steps['onehot']))
2757198591872
2755226729104
看起来 ColumnTranformer
在拟合之前克隆了它的转换器。
关于python - 为什么 ColumnTransformer 不在其转换器上调用 fit?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56556148/