【发布时间】:2022-01-19 09:05:09
【问题描述】:
我正在使用 XGBoost 特征重要性分数在我的 KNN 模型中使用以下代码 (taken from this article) 执行特征选择:
# this section for training and testing the algorithm after feature selection
#dataset spliting
X = df.iloc[:, 0:17]
y_bin = df.iloc[:, 17]
# spliting the dataset into train, test and validate for binary classification
X_train, X_test, y_bin_train, y_bin_test = train_test_split(X, y_bin, random_state=0, test_size=0.2)
# fit model on training data
model = XGBClassifier()
model.fit(X_train, y_bin_train)
# using normalization technique to feature scale the training data
norm = MinMaxScaler()
X_train= norm.fit_transform(X_train)
X_test= norm.transform(X_test)
#oversampling
smote= SMOTE()
X_train, y_bin_train = smote.fit_resample(X_train,y_bin_train)
# Fit model using each importance as a threshold
thresholds = sort(model.feature_importances_)
for thresh in thresholds:
# select features using threshold
selection = SelectFromModel(model, threshold=thresh, prefit=True)
select_X_train = selection.transform(X_train)
# train model
knn = KNeighborsClassifier(n_neighbors=3, metric='euclidean')
knn.fit(select_X_train, y_bin_train)
# eval model
select_X_test = selection.transform(X_test)
y_pred = knn.predict(select_X_test)
report = classification_report(y_bin_test,y_pred)
print("Thresh= {} , n= {}\n {}" .format(thresh, select_X_train.shape[1], report))
cm = confusion_matrix(y_bin_test, y_pred)
print(cm)
我得到的输出显示了每次迭代使用的特征数量select_X_train.shape[1]、每次删除特征时使用的阈值thresh、分类报告和混淆矩阵:
Thresh= 0.0 , n= 17
precision recall f1-score support
0 0.98 0.96 0.97 42930
1 0.87 0.92 0.89 11996
accuracy 0.95 54926
macro avg 0.92 0.94 0.93 54926
weighted avg 0.95 0.95 0.95 54926
[[41226 1704]
[ 909 11087]]
Thresh= 0.007143254857510328 , n= 16
precision recall f1-score support
0 0.98 0.96 0.97 42930
1 0.87 0.92 0.89 11996
accuracy 0.95 54926
macro avg 0.92 0.94 0.93 54926
weighted avg 0.95 0.95 0.95 54926
[[41226 1704]
[ 909 11087]]
此输出将一直持续到使用的特征数达到 1 (n=1)。 我想要做的是我还想在每次迭代中包含使用(或删除)的功能的名称,但我无法弄清楚。 有没有办法完成它?
【问题讨论】:
标签: python machine-learning scikit-learn xgboost knn