【问题标题】:Get feature names after sklearn pipeline在 sklearn 管道之后获取特征名称
【发布时间】:2022-02-09 19:13:19
【问题描述】:

我想将输出的 np 数组与特征相匹配,以制作一个新的 pandas 数据框

这是我的管道:

from sklearn.pipeline import Pipeline
# Categorical pipeline
categorical_preprocessing = Pipeline(
[
    ('Imputation', SimpleImputer(missing_values=np.nan, strategy='most_frequent')),
    ('Ordinal encoding', OrdinalEncoder(handle_unknown='use_encoded_value', unknown_value=-1)),
]
)
# Continuous pipeline
continuous_preprocessing = Pipeline(
[
     ('Imputation', SimpleImputer(missing_values=np.nan, strategy='mean')),
     ('Scaling', StandardScaler())
]
)
# Creating preprocessing pipeline
preprocessing = make_column_transformer(
     (continuous_preprocessing, continuous_cols),
     (categorical_preprocessing, categorical_cols),
)
# Final pipeline
pipeline = Pipeline(
[('Preprocessing', preprocessing)]
)

我是这样称呼它的:

X_train = pipeline.fit_transform(X_train)
X_val = pipeline.transform(X_val)
X_test = pipeline.transform(X_test)

这是我在尝试获取功能名称时得到的结果:

pipeline['Preprocessing'].transformers_[1][1]['Ordinal encoding'].get_feature_names()

输出:

AttributeError: 'OrdinalEncoder' object has no attribute 'get_feature_names'

这是一个类似的 SO 问题:Sklearn Pipeline: Get feature names after OneHotEncode In ColumnTransformer

【问题讨论】:

  • 你的sklearn 版本是什么?
  • @ScottBoston 我没有使用计数矢量化器,我什至没有文本数据。我了解一些 sklearn 方法具有获取特征名称,但我如何确定结果数据集中的列和列名匹配?
  • @richardec 最新版本。

标签: python pandas scikit-learn


【解决方案1】:

关键是,截至今天,一些转换器确实公开了一个方法 .get_feature_names_out(),而另一些则没有,这会产生一些问题 - 例如 - 每当您想要创建一个格式良好的 DataFrame 来自 Pipeline 或 ColumnTransformer 实例输出的 np.array。 (相反,afaik,.get_feature_names() 在最新版本中被弃用,取而代之的是 .get_feature_names_out())。

关于您使用的转换器,StandardScaler 属于公开方法的第一类转换器,而 SimpleImputer 和 OrdinalEncoder 都属于第二类。文档在 Methods 段落中显示了公开的方法。如前所述,这在您的pipeline 上执行pd.DataFrame(pipeline.fit_transform(X_train), columns=pipeline.get_feature_names_out()) 之类的操作时会导致问题,但它也会在您的categorical_preprocessing 和continuous_preprocessing 管道上导致问题(因为在这两种情况下,至少有一个变压器缺少该方法)并在 preprocessing ColumnTransformer 实例上。

sklearn 一直在尝试使用.get_feature_names_out() 方法丰富所有 估计器。它在github issue #21308 中进行跟踪,正如您可能看到的,它在许多 PR 中分支(每个 PR 处理一个特定的模块)。例如,issue #21079 用于 preprocessing 模块,这将丰富 OrdinalEncoder 等等,issue #21078 用于 impute 模块,这将丰富 @987654349 @。我想一旦所有引用的 PR 都被合并,它们就会在新版本中可用。

与此同时,imo,您应该使用可能满足您需求的自定义解决方案。这是一个简单的示例,它不一定符合您的需求,但旨在提供一种(可能的)处理方式:

import pandas as pd
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OrdinalEncoder, StandardScaler
from sklearn.compose import make_column_transformer, make_column_selector

X = pd.DataFrame({'city': ['London', 'London', 'Paris', 'Sallisaw', ''],
                  'title': ['His Last Bow', 'How Watson Learned the Trick', 'A Moveable Feast', 'The Grapes of Wrath', 'The Jungle'],
                  'expert_rating': [5, 3, 4, 5, np.NaN],
                  'user_rating': [4, 5, 4, np.NaN, 3]})
X

num_cols = X.select_dtypes(include=np.number).columns.tolist()
cat_cols = X.select_dtypes(exclude=np.number).columns.tolist()

# Categorical pipeline
categorical_preprocessing = Pipeline(
[
    ('Imputation', SimpleImputer(missing_values='', strategy='most_frequent')),
    ('Ordinal encoding', OrdinalEncoder(handle_unknown='use_encoded_value', unknown_value=-1)),
]
)
# Continuous pipeline
continuous_preprocessing = Pipeline(
[
    ('Imputation', SimpleImputer(missing_values=np.nan, strategy='mean')),
    ('Scaling', StandardScaler())
]
)
# Creating preprocessing pipeline
preprocessing = make_column_transformer(
    (continuous_preprocessing, num_cols),
    (categorical_preprocessing, cat_cols),
)

# Final pipeline
pipeline = Pipeline(
    [('Preprocessing', preprocessing)]
)

X_trans = pipeline.fit_transform(X)

pd.DataFrame(X_trans, columns= num_cols + cat_cols)

【讨论】:

  • 谢谢,我做了类似的事情,我只是将列的名称分配给新创建的 df
猜你喜欢
  • 2018-09-01
  • 2019-07-05
  • 2016-08-06
  • 2014-09-20
  • 2019-08-10
  • 2019-09-04
  • 2017-12-29
  • 2017-12-23
  • 2017-11-21
相关资源
最近更新 更多