Gid*_*per 5 python pipeline python-3.x random-forest scikit-learn
我想知道在预处理管道中使用分类器时,如何从 scikit-learn 中的随机森林中提取特征重要性以及特征名称。
这里的问题仅涉及提取特征重要性:如何从 Sklearn pipeline 中提取特征重要性
从我所做的简短研究来看,这在 scikit-learn 中似乎不可能,但我希望我是错的。
我还发现了一个名为 ELI5 的包(https://eli5.readthedocs.io/en/latest/overview.html),它应该可以解决 scikit-learn 的问题,但它并没有解决我的问题,因为名称为我输出的特征是 x1、x2 等,而不是实际的特征名称。
作为一种解决方法,我在管道之外完成了所有预处理,但很想知道如何在管道中进行预处理。
如果我可以提供任何有用的代码,请在评论中告诉我。
有一个使用 Xgboost 获取特征重要性的示例:
num_transformer = Pipeline(steps=[
                  ('imputer', SimpleImputer(strategy='median')),
                  ('scaler', preprocessing.RobustScaler())])
cat_transformer = Pipeline(steps=[
                  ('imputer', SimpleImputer(strategy='most_frequent')),
                  ('onehot', preprocessing.OneHotEncoder(categories='auto', 
                                     sparse=False, 
                                     handle_unknown='ignore'))])
from sklearn.compose import ColumnTransformer
numerical_columns = X.columns[X.dtypes != 'category'].tolist()
categorical_columns = X.columns[X.dtypes == 'category'].tolist()
pipeline_procesado = ColumnTransformer(transformers=[
            ('numerical_preprocessing', num_transformer, numerical_columns),
       ('categorical_preprocessing', cat_transformer, categorical_columns)],
        remainder='passthrough',
        verbose=True)
# Create the classifier
classifier = XGBClassifier()
# Create the overall model as a single pipeline
pipeline = Pipeline([("transform_inputs", pipeline_procesado), ("classifier", 
classifier)])
pipeline.fit(X_train, y_train)
onehot_columns = pipeline.named_steps['transform_inputs'].named_transformers_['categorical_preprocessing'].named_steps['onehot'].get_feature_names(input_features=categorical_columns)
#you can get the values transformed with your pipeline
X_values = pipeline_procesado.fit_transform(X_train)
df_from_array_pipeline = pd.DataFrame(X_values, columns = numerical_columns + list(onehot_columns) )
feature_importance = pd.Series(data= pipeline.named_steps['classifier'].feature_importances_, index = np.array(numerical_columns + list(onehot_columns)))