我已经在 Internet 上多次看到这个主题,但从未见过一个完整、全面的解决方案,它可以适用于当前库版本的 sklearn 的所有用例。有人可以尝试使用以下示例解释如何实现吗?
In this example I'm using the following dataset
data = pd.read_csv('heart.csv')
# Preparing individual pipelines for numerical and categorical features
pipe_numeric = Pipeline(steps=[
('impute_num', SimpleImputer(
missing_values = np.nan,
strategy = 'median',
copy = False,
add_indicator = True)
)
])
pipe_categorical = Pipeline(steps=[
('impute_cat', SimpleImputer(
missing_values = np.nan,
strategy = 'constant',
fill_value = 99999,
copy = False)
),
('one_hot', OneHotEncoder(handle_unknown='ignore'))
])
# Combining them into a transformer
transformer_union = ColumnTransformer([
('feat_numeric', pipe_numeric, ['age']),
('feat_categorical', pipe_categorical, ['cp']),
], remainder = 'passthrough')
# Fitting the transformer
transformer_union.fit(data)
# We can then apply and get the data in the following way
transformer_union.transform(data)
# And it has the following shape
transformer_union.transform(data).shape
现在出现了主要问题:如何有效地将输出的 numpy 数组与所有转换产生的新列名结合起来?这个例子虽然需要相当多的工作,但仍然相对简单,但是对于更大的管道,这可能会变得更加复杂。
# Transformers object
transformers = transformer_union.named_transformers_
# Categorical features (from transformer)
transformers['feat_categorical'].named_steps['one_hot'].get_feature_names()
# Numerical features (from transformer) - no names are available?
transformers['feat_numeric'].named_steps['impute_num']
# All the other columns that were not transformed - no names are available?
transformers['remainder']
我已经检查了各种不同的示例,但似乎没有任何 Elixir :
我对 sklearn 的管理方式有点惊讶 - 在 R 中的
tidymodels
生态系统(它仍在开发中,但无论如何),这很容易用 prep
和 bake
方法。我想它可以以某种方式类似地完成。全面检查最终输出对于数据科学工作至关重要——有人可以就最佳路径提出建议吗?
最佳答案
sklearn 开发人员正在为此努力;讨论涵盖多个 SLEP 和许多问题。已经取得了一些进展,一些变压器正在实现 get_features_names
当输入是 Pandas 数据框时,其他具有跟踪列名的内部属性。 ColumnTransformer
确实有 get_feature_names
, 但是 Pipeline
没有,所以它会在你的例子中失败。
目前最完整的解决方案似乎是sklearn-pandas
:
https://github.com/scikit-learn-contrib/sklearn-pandas
另一个有趣的方法隐藏在 eli5
中。 .在他们的explain_weights
,它们有一个通用函数 transform_feature_names
.它有一些专门的调度,但除此之外尝试调用 get_feature_names
;最值得注意的是,有一个 Pipeline
的调度。 .不幸的是,目前这将在使用 Pipeline 作为转换器的 ColumnTransformer 上失败;见 https://stackoverflow.com/a/62124484/10495893举个例子和一个潜在的解决方法。
关于python - 使用 ColumnTransformer/FeatureUnion 后构建完整数据框(特征值 + 名称)的推荐方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58989517/