我正在用 python 构建一个预测模型,其中包含两个独立的训练集和测试集。训练数据包含数字类型分类变量,例如邮政编码,[91521,23151,12355, ...],以及字符串分类变量,例如城市['芝加哥','纽约','洛杉矶', ...]。
为了训练数据,我首先使用“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
您还可以获取缺失的列并将它们添加到测试数据集中:
# 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]
此代码还确保从测试数据集中的类别生成但不存在于训练数据集中的列将被删除
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)