python - 在训练和测试集中具有不同级别的管道中创建虚拟对象

标签 python pandas scikit-learn

我目前正在探索 scikit 学习管道。 我还想用管道预处理数据。 但是,我的火车和测试数据具有不同级别的分类变量。 例子: 考虑:

import pandas as pd
train = pd.Series(list('abbaa'))
test = pd.Series(list('abcd'))

我用 pandas 写了一个 TransformerMixinClass

class CreateDummies(TransformerMixin):

def transform(self, X, **transformparams):
    return pd.get_dummies(X).copy()

def fit(self, X, y=None, **fitparams):
    return self

fit_transform 产生 2 列训练数据和 4 列测试数据。所以这里并不奇怪,但不适合管道

同样,我尝试导入标签编码器(以及可能的后续步骤的 OneHotEncoder):

from sklearn.preprocessing import LabelEncoder, OneHotEncoder
le = LabelEncoder()
le.fit_transform(train)
le.transform(test)

毫不奇怪,这会产生一个错误。

所以这里的问题是我需要测试集中包含的一些信息。 有什么好的方法可以将其包含在管道中吗?

最佳答案

您可以按照 this answer 中的说明使用分类:

categories = np.union1d(train, test)
train = train.astype('category', categories=categories)
test = test.astype('category', categories=categories)

pd.get_dummies(train)
Out: 
   a  b  c  d
0  1  0  0  0
1  0  1  0  0
2  0  1  0  0
3  1  0  0  0
4  1  0  0  0

pd.get_dummies(test)
Out: 
   a  b  c  d
0  1  0  0  0
1  0  1  0  0
2  0  0  1  0
3  0  0  0  1

关于python - 在训练和测试集中具有不同级别的管道中创建虚拟对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39804733/

相关文章:

python - 将多个自定义类与 Pipeline sklearn (Python) 结合使用

python - 从 Python 执行存储过程

python - 我的 python 脚本和 cron 作业有什么问题?

python - Django 中的自定义标记

python - 如何在 Wine 模拟的 python 版本(在 docker 容器内)中正确安装和运行 pip?

python - 在 scikit 中获得训练时间

python - Pandas 将系列分配给多索引的新列

python-3.x - python : I want to fill the null values only where the whole row is null

python - 如何复制 Pandas 数据帧以匹配其他数据帧长度?

python - StandardScaler 如何不破坏数据完整性?