python - 带有 OHE 的 ColumnTransformer 和 Pipeline - 执行 ct 后 OHE 编码字段是保留还是删除?

标签 python scikit-learn pipeline

CT 文档:

remainder{‘drop’, ‘passthrough’} or estimator, default=’drop’

By default, only the specified columns in transformers are transformed and combined in the output, and the non-specified columns are dropped. (default of 'drop'). By specifying remainder='passthrough', all remaining columns that were not specified in transformers will be automatically passed through. This subset of columns is concatenated with the output of the transformers. By setting remainder to be an estimator, the remaining non-specified columns will use the remainder estimator. The estimator must support fit and transform. Note that using this feature requires that the DataFrame columns input at fit and transform have identical order.

我相信这个剩余=与 OneHot 编码的字段无关。我想知道 OHE 字段(例如“CatX”)是如何处理的。

当我进行独立 CT 变换时,我发现“CatX”没有出现在输出中。

ct = ColumnTransformer(transformers=[('OHE',ohe,ohe_col)],remainder='passthrough')

当我重复 OHE 进行独立 CT 时,它是成功的(即 OHE 2 次)。这告诉我,在 CT 内,该字段仍然可用,但仅在退出 CT 时删除。

ct = ColumnTransformer(transformers=[('OHE',ohe,ohe_col),('OHE1',ohe,ohe_col)],
remainder='passthrough')

然后我尝试将其放入管道中,我尝试进行两次 CT。这是令人困惑的部分。它过去了。这告诉我第一个 CT1 将“CatX”传递给 CT2。

ct = ColumnTransformer(transformers=[('OHE',ohe,ohe_col)],remainder='passthrough')    
Pipeline([('ct1',ct),('ct2',ct)('model',v)])

问题:

  1. 使用 Pipeline 时,谁控制 CT 是否在退出时通过“CatX”?
  2. 使用 Pipeline 时,如果传递的是“CatX”,那么模型是否无法处理它?<​​/li>

我希望我的问题很清楚。感谢您提前的答复。

最佳答案

ColumnTransformer 旨在通过指定的转换来转换数组或数据帧的列。这意味着安装后您将不再拥有原始列。

import pandas as pd
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.preprocessing import OneHotEncoder

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

ct = ColumnTransformer(transformers=[
    ('ohe', OneHotEncoder(), make_column_selector(pattern='city'))], 
    remainder='passthrough', verbose_feature_names_out=False)

pd.DataFrame(ct.fit_transform(X), columns=ct.get_feature_names_out())

enter image description here

同时,您应该意识到 ColumnTransformer 并行应用其转换器,这就是为什么在第二个示例中您会看到 OHE 应用的原因两次,即因为两个 OHE 转换器都作用于原始数据。关于此有一些有趣的帖子,请参阅hereherehere例如。

因此,这将是通过 ColumnTransformer 应用两次转换的结果:

ct_d = ColumnTransformer(transformers=[
    ('ohe1', OneHotEncoder(), make_column_selector(pattern='city')),
    ('ohe2', OneHotEncoder(), make_column_selector(pattern='city'))], 
    remainder='passthrough', verbose_feature_names_out=True)

pd.DataFrame(ct_d.fit_transform(X), columns=ct_d.get_feature_names_out())

enter image description here

然后,我不确定在使用Pipeline时我是否正确地理解了您的问题(也许添加一些详细信息可能有用,或者我可能会忽略某些内容)。这就是我在避免传递 ColumnTransformer 实例时得到的结果;您将不再找到原始列,因为 OneHotEncoder 将其删除。

from sklearn.pipeline import Pipeline

pipe_new = Pipeline([('ohe', OneHotEncoder())])
pd.DataFrame(pipe_new.fit_transform(pd.DataFrame(X['city'])).toarray())

enter image description here

另一方面,下面的示例可能类似于您对Pipeline 的使用。也就是说,city 列在 ct1 中进行单热编码,并且其输出(实际上是其输出的第 0 列)在 ct2 时经历相同的命运> 被应用(并且其余列被传递)。更具体地说,ct1 输出 (np.array([1.0, 1.0, 0.0, 0.0]).T) 的第 0 列被 one-hot 编码为 np.array([[0.0, 0.0, 1.0, 1.0], [1.0, 1.0, 0.0, 0.0]]).T (实际上它不会是一个 np 数组,我这样写这只是为了便于表示)。

ct = ColumnTransformer(transformers=[
    ('ohe', OneHotEncoder(), [0])], remainder='passthrough', verbose_feature_names_out=False)

pipe = Pipeline([
    ('ct1', ct),
    ('ct2', ct)
])

pd.DataFrame(pipe.fit_transform(X))

enter image description here

关于python - 带有 OHE 的 ColumnTransformer 和 Pipeline - 执行 ct 后 OHE 编码字段是保留还是删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70527088/

相关文章:

python - Django:如何动态创建模型仅用于测试

python - 正则表达式替换文本之前和之后,保持文本就位

python - 使用pipeline时为什么不改造X_test

python - 完整的 sklearn 管道示例

python - 分配到列表列表中的位置

Python/Django : How to Prepend a # on to all URLS

python - Sklearn TruncatedSVD 不返回 n,组件

machine-learning - 图像聚类的亲和性传播

scala - 安装管道并处理数据

deployment - 无法将 Kubernetes 部署链接到 GitLab 环境页面