如何从嵌入 ColumnTransformer 中的 OneHotEncoder 获取功能名称?
下面这段代码:
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
df = pd.DataFrame(data = [[1],[2]], columns = ['C'])
ohe = OneHotEncoder(sparse_output = False)
transformer = ColumnTransformer(transformers = [('encoder', ohe, ['C'])])
transformer.fit_transform(df)
ohe.get_feature_names_out()
结果出现以下错误消息:
NotFittedError Traceback (most recent call last)
<ipython-input-1-46f41a3cf71a> in <cell line: 10>()
8 transformer = ColumnTransformer(transformers = [('encoder', ohe, ['C'])])
9 transformer.fit_transform(df)
---> 10 ohe.get_feature_names_out()
1 frames
/usr/local/lib/python3.10/dist-packages/sklearn/utils/validation.py in check_is_fitted(estimator, attributes, msg, all_or_any)
1388
1389 if not fitted:
-> 1390 raise NotFittedError(msg % {"name": type(estimator).__name__})
1391
1392
NotFittedError: This OneHotEncoder instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.
为什么?
ColumnTransformer
克隆它的变形金刚,所以你的ohe
确实仍然不适合。您可以通过多种方式访问(安装的)组件,例如还要注意它
ColumnTransformer
本身有一个get_feature_names_out
方法。