特征选择python之后的预测

时间:2016-04-06 20:00:37

标签: python machine-learning scikit-learn data-modeling feature-selection

我正在尝试使用python构建预测模型。训练和测试数据集有400多个变量。在训练数据集上使用特征选择时,变量的数量减少到180

from sklearn.feature_selection import VarianceThreshold
sel = VarianceThreshold(threshold = .9)

然后我使用梯度增强算法训练模型,在交叉验证中实现.84 AUC准确度。

from sklearn import ensemble
from 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,这是非常差的。 谢谢!

1 个答案:

答案 0 :(得分:2)

您也应该通过特征选择转换预测矩阵。所以你的代码中的某个地方

df = sel.fit_transform(X)

并且在预测之前

df_prediction = sel.transform(X_prediction)