从Sklearn管道中用特征名称提取特征重要性

2024-09-26 17:45:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道,当使用管道中的分类器进行预处理时,如何从scikit learn中的随机林中提取具有特征名的特征重要性。在

这里的问题是只提取特征重要性:How to extract feature importances from an Sklearn pipeline

从我所做的简短研究来看,这在scikit learn中似乎不可能实现,但我希望我错了。在

我还发现了一个名为ELI5(https://eli5.readthedocs.io/en/latest/overview.html)的包,它应该用scikit learn解决这个问题,但它没有解决我的问题,因为为我输出的特性名称是x1、x2等,而不是实际的特性名称。在

作为一种解决方法,我在管道之外完成了所有的预处理,但是我很想知道如何在管道中进行预处理。在

如果我能提供任何有用的代码,请在评论中告诉我。在


Tags: tofrom名称管道分类器extract特征特性
1条回答
网友
1楼 · 发布于 2024-09-26 17:45:56

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)))

相关问题 更多 >

    热门问题