我正在尝试对我的数据集应用插补和热一种编码。我知道在应用插补时,数据的维度可能会发生变化,因此我手动处理了它。该模型运行良好,但后来我决定应用热一种编码。现在,该程序无法编译。我收到尺寸不匹配错误。
test_X = pd.get_dummies(test)
train_X = pd.get_dummies(train)
col_with_missingVal = (col for col in train_X.columns if train_X[col].isnull().any())
for col in col_with_missingVal:
train_X[col + 'is_missing'] = train_X[col].isnull()
test_X[col + 'is_missing'] = test_X[col].isnull()
#impute the data
imputer = Imputer()
imp_train_X = pd.DataFrame(imputer.fit_transform(train_X))
imp_test_X = pd.DataFrame(imputer.fit_transform(test_X))
imp_train_X.columns = train_X.columns
imp_test_X.columns = test_X.columns
#Fit the model
my_model = RandomForestRegressor()
my_model.fit(imp_train_X, train_y)
# Use the model to make predictions
predicted_prices = my_model.predict(imp_test_X)
我在最后一行代码中收到以下错误:
ValueError: Number of features of the model must match the input. Model n_features is 293 and input n_features is 274
出现此错误的原因是什么?如何解决?
问题出在前两行。pd.get_dummies()
如果训练和测试中的数据不同,将返回不同的列。
例如,如果在训练中,一列有 3 个类别,则将为它们创建 3 列,但可能会发生测试数据仅包含该特定列中的 2 个类别,因为在该列之后您将得到 2 列pd.get_dummies()
。这将导致不同数量的列。
您可以在这里执行以下操作:
1) Easiest Use pd.get_dummies()
在训练测试之前对整个数据进行分割,然后分割数据。但不推荐这样做,因为它会将测试数据的信息泄露给模型。
2)如果可以使用scikit的开发版本,则使用分类编码器执行单热编码。
3)在当前scikit版本中使用LabelEncoder + OneHotEncoder的组合来实现相同的效果。看我的另一个答案例如。
Note
也只能打电话transform()
就测试数据而言,从来没有fit()
。做这个:-
# If you call fit_transform(), the imputer will again learn the
# new mean from the test data
# Which will lead to differences and data leakage.
imp_test_X = pd.DataFrame(imputer.transform(test_X))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)