这种检查没有通用的解决方案,因为管道可以由非常不同的步骤和非常不同的数据处理步骤组成,例如插补、矢量化、特征编码等。因此,每个步骤的可用信息可能非常不同。
因此,我认为最好的方法是通过变压器安装后将暴露的属性或变压器检索信息的专用方法分别检查每个步骤。
假设您有以下数据和管道:
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder
from sklearn.pipeline importPipeline
import numpy as np
X = [['Male', 1, 7], ['Female', 3, 5], ['Female', 2, 12], [np.nan, 2, 4], ['Male', np.nan, 15]]
pipeline = Pipeline(steps=[
('imputation', ColumnTransformer(transformers=[
('categorical', SimpleImputer(strategy='constant', fill_value='Missing'), [0]),
('numeric', SimpleImputer(strategy='mean'), [1, 2])
])),
('encoding', OneHotEncoder(handle_unknown='ignore'))
])
Xt = pipeline.fit_transform(X)
那么最好检查一下具体步骤的属性:
>>> print(pipeline['imputation'].transformers_[1][1].statistics_) # computed mean for features 1 and 2
[2. 8.6]
>>> print(pipeline['encoding'].get_feature_names()) # names of encoded categories
[... 'x2_Female' 'x2_Male' 'x2_Missing']
这当然假设您知道您的管道是如何组成的,以及在拟合后每个步骤将公开哪些属性以及它提供了哪些其他方法(scikit-learn 的文档是查找的最佳位置)。