我正在尝试使用 Python 构建一个预测模型。训练和测试数据集有超过 400 个变量。在对训练数据集进行特征选择后,变量数量减少到 180 个。
from sklearn.feature_selection import VarianceThresholdsel = VarianceThreshold(threshold = .9)
然后,我使用梯度提升算法训练模型,在交叉验证中达到了 0.84 的 AUC 准确率。
from sklearn import ensemblefrom sklearn.cross_validation import train_test_split from sklearn.metrics import roc_auc_score as auc df_fit, df_eval, y_fit, y_eval= train_test_split( df, y, test_size=0.2, random_state=1 )boosting_model = ensemble.GradientBoostingClassifier(n_estimators=100, max_depth=3, min_samples_leaf=100, learning_rate=0.1, subsample=0.5, random_state=1)boosting_model.fit(df_fit, y_fit)
但是,当我尝试使用这个模型对预测数据集进行预测时,出现了错误
predict_target = boosting_model.predict(df_prediction)Error: Number of variables in prediction data set 'df_prediction' does not match the number of variables in the model
这是有道理的,因为测试数据中的总变量仍然超过 400 个。我的问题是,有没有办法绕过这个问题,继续使用特征选择进行预测建模。因为如果我去掉特征选择,模型的准确率会下降到 0.5,这非常差。谢谢!
回答:
你应该通过特征选择来转换你的预测矩阵。所以在你的代码中某处你需要这样做
df = sel.fit_transform(X)
并且在预测之前
df_prediction = sel.transform(X_prediction)