KeyError:权重。仅在特征重要性选择的特征上实现XGBoost
我在使用XGBoost的特征重要性功能时,得到了我数据集中X_train的特征重要性评分。我的X_train最开始有49个特征。XGBoost的特征重要性告诉我这49个特征中,每个特征的重要性得分是多少。现在我想知道在我的机器学习模型中应该使用多少个特征。每个特征对应的阈值在一个数组中列出。我想知道我应该选择哪个最低的阈值来包含特征。比如,我是应该包含所有得分在0.3以上的特征,还是0.4以上的特征等等。不过,我遇到了一个错误:
from numpy import sort
from sklearn.feature_selection import SelectFromModel
xgb_model = xgb.XGBClassifier(max_depth=5, learning_rate=0.08, n_jobs=-1).fit(X_train, y_train)
thresholds = sort(xgb_model.feature_importances_)
所有特征的阈值如下:
[IN]thresholds
[OUT] array([0. , 0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. , 0. ,
0.00201289, 0.00362736, 0.0036676 , 0.00467797, 0.00532952,
0.00591741, 0.00630169, 0.00661084, 0.00737418, 0.00741502,
0.00748773, 0.00753344, 0.00773079, 0.00852909, 0.00859741,
0.00906814, 0.00929257, 0.00980796, 0.00986394, 0.01056027,
0.01154695, 0.01190695, 0.01203871, 0.01258377, 0.01301482,
0.01383268, 0.01390096, 0.02001457, 0.02699436, 0.03168892,
0.03543754, 0.03578222, 0.13946259, 0.48038903], dtype=float32)
这是一个函数,用来选择最重要的特征,并创建一个名为select_X_train的数据框,里面包含这些特征。
for thresh in thresholds:
# select features using threshold
selection = SelectFromModel(xgb_model, threshold=thresh, prefit=True)
select_X_train = selection.transform(X_train)
# train model
selection_model = XGBClassifier()
selection_model.fit(select_X_train, y_train)
# eval model
select_X_test = selection.transform(X_test)
y_pred = selection_model.predict(select_X_test)
predictions = [round(value) for value in y_pred]
accuracy = accuracy_score(y_test, predictions)
print("Thresh=%.3f, n=%d, Accuracy: %.2f%%" % (thresh, select_X_train.shape[1], accuracy*100.0))
我遇到的错误如下:
----> 4 select_X_train = selection.transform(X_train)
KeyError: 'weight'
没有名为weight的列。怎么解决这个错误呢?
期望的输出结果
Thresh=0.00201289, n=33, Accuracy: 77.95%
#33 features with threshold above 0.002
Thresh=0.00362736, n=34, Accuracy: 76.38%
#34 features with threshold above 0.003
Thresh=0.0036676 , n=35, Accuracy: 77.56%
#35 features with threshold above 0.003 and so on
基本上就是取每个阈值,运行XGBoost,并计算所有特征在指定的最低阈值得分下的准确率。例如,在第一个情况下,所有得分至少为0.00201289的特征都会被考虑进XGBoost,然后计算准确率。接下来,得分至少为0.003的特征也会被考虑,依此类推。
相关问题:
- 暂无相关问题
1 个回答
0
我在跟着一个类似的教程,成功地通过降低版本到 xgboost==0.90 来实现了这个特征选择的功能。
另外,为了避免一些烦人的警告,可以使用 XGClassifier(objective ='reg:squarederror')