python - 在训练和测试数据中保持相同的虚拟变量

标签 python dataframe scikit-learn prediction dummy-variable

我正在 python 中构建一个预测模型,其中包含两个单独的训练集和测试集。训练数据包含数字类型的分类变量,例如邮政编码,[91521,23151,12355, ...],还有字符串分类变量,例如,城市 ['Chicago', 'New York', 'Los Angeles', ...]。

为了训练数据,我首先使用 'pd.get_dummies' 来获取这些变量的虚拟变量,然后用转换后的训练数据拟合模型。

我对我的测试数据进行相同的转换,并使用经过训练的模型预测结果。但是,我得到了错误

ValueError: Number of features of the model must  match the input. Model n_features is 1487 and  input n_features is 1345

原因是测试数据中的虚拟变量较少,因为它的“城市”和“邮政编码”较少。

我该如何解决这个问题?例如,'OneHotEncoder' 只会对所有数值类型的分类变量进行编码。 'DictVectorizer()' 只会对所有字符串类型的分类变量进行编码。我在网上搜索并看到一些类似的问题,但没有一个能真正解决我的问题。

Handling categorical features using scikit-learn

https://www.quora.com/If-the-training-dataset-has-more-variables-than-the-test-dataset-what-does-one-do

https://www.quora.com/What-is-the-best-way-to-do-a-binary-one-hot-one-of-K-coding-in-Python

最佳答案

您也可以只获取缺失的列并将它们添加到测试数据集中:

# Get missing columns in the training test
missing_cols = set( train.columns ) - set( test.columns )
# Add a missing column in test set with default value equal to 0
for c in missing_cols:
    test[c] = 0
# Ensure the order of column in the test set is in the same order than in train set
test = test[train.columns]

此代码还确保将删除从测试数据集中的类别产生但不存在于训练数据集中的列

关于python - 在训练和测试数据中保持相同的虚拟变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41335718/

相关文章:

android - 构建apk时cocos 2d-x-3.5错误: EOFError: EOF when reading a line

python - 如何在 tf.estimator.Estimator() 中记录 tensorflow 层输出

python - 一列中每次出现的值在另一列中的总和

scikit-learn - 将 sklearn TfidfVectorizer 与已经标记化的输入一起使用?

python - Django 表单继承不起作用 __init__

python - NumPy vs Cython - 嵌套循环这么慢?

python - groupby 多个值列

r - 沿着数据框行滑动并将行与下一行进行比较

python - 如何对具有两个值的列进行单热编码?

scikit-learn - scikit-learn 中的 Nu_SVR 没有详细信息