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

新手上路,请多包涵

我正在用两个独立的训练和测试集在 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()’ 只会对所有字符串类型的分类变量进行编码。我在网上搜索并看到了一些类似的问题,但没有一个真正解决了我的问题。

使用 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

原文由 nimning 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 363
1 个回答

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

 # 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]

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

原文由 Thibault Clement 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题