Kon*_*sch 5 python pandas scikit-learn
我在 Internet 上多次看到这个主题,但从未见过一个完整、全面的解决方案,可以在所有用例中使用 sklearn 的当前库版本。有人可以尝试使用以下示例来解释应该如何实现吗?
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
Run Code Online (Sandbox Code Playgroud)
现在的主要问题是:如何有效地将输出 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']
Run Code Online (Sandbox Code Playgroud)
我检查了各种不同的例子,似乎没有任何灵丹妙药:
sklearn 本身不支持这一点 - 无法获得可以轻松与数组组合成新 DF 的列名对齐向量,但也许我错了 - 如果是这种情况,任何人都可以指出我的资源?
有些人正在实施他们的自定义转换器/管道,但是当您想要构建大型管道时,这会变得有点忙
是否有其他与 sklearn 相关的软件包可以缓解该问题?
我对 sklearn 的管理方式感到有点惊讶 - 在tidymodels
生态系统中的 R 中(它仍在开发中,但尽管如此),使用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 上会失败;有关示例和潜在的解决方法,请参阅/sf/answers/4348713911/ 。
归档时间: |
|
查看次数: |
89 次 |
最近记录: |