Skip to main content
 首页 » 编程设计

python之特征选择python后的预测

2024年10月24日7shangdawei

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

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

然后我使用梯度提升算法训练模型,在交叉验证中达到 0.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,这是非常差的。 谢谢!

请您参考如下方法:

您也应该通过特征选择来转换预测矩阵。所以在你的代码中的某处你做

df = sel.fit_transform(X) 

在预测之前

df_prediction = sel.transform(X_prediction)