XGBoost库
Python中,可直接通过“pip install xgboost”安装XGBoost库,基分类器支持决策树和线性分类器。
2
XGBoost代码实现
本例中我们使用uci上的酒质量评价数据,该数据通过酸性、ph值、酒精度等11个维度对酒的品质进行评价,对酒的评分为0-10分。
-
相关库载入
除了xgboost,本例中我们还将用到pandas、sklearn和matplotlib方便数据的读入、处理和最后的图像绘制。
import xgboostimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn import metricsfrom xgboost import plot_importancefrom matplotlib import pyplot
-
数据加载
将数据导入Python,并对数据根据7:3的比例划分为训练集和测试集,并对label进行处理,超过6分为1,否则为0。
redwine = pd.read_csv(\'winequality-red.csv\',sep = \';\')whitewine = pd.read_csv(\'winequality-white.csv\',sep = \';\')wine = redwine.append(whitewine)x = wine.iloc[:,0:11]y = wine.iloc[:,11]y[y<=6] = 0y[y>6] =1# test_size: 测试集大小# random_state: 设置随机数种子,0或不填则每次划分结果不同train_x,test_x,train_y,test_y = train_test_split(x,y,test_size=0.3, random_state=17)
-
数据预处理
将数据转化为xgb.DMatrix类型。
dtrain = xgboost.DMatrix(data = train_x, label = train_y)dtest = xgboost.DMatrix(data = test_x, label = test_y)
-
模型训练
训练模型,并对特征进行重要性排序。
param = {\'max_depth\':6, \'eta\':0.5, \'silent\':0, \'objective\':\'binary:logistic\' }num_round = 2xgb = xgboost.train(param,dtrain, num_round)test_preds = xgb.predict(dtest)test_predictions = [round(value) for value in test_preds] #变成0、1 #显示特征重要性plot_importance(xgb)#打印重要程度结果pyplot.show()
-
测试集效果检验
计算准确率、召回率等指标,并绘制ROC曲线图。
test_accuracy = metrics.accuracy_score(test_y, test_predictions) #准确率
test_auc = metrics.roc_auc_score(test_y,test_preds) #auc
test_recall = metrics.recall_score(test_y,test_predictions) #召回率
test_f1 = metrics.f1_score(test_y,test_predictions) #f1
test_precision = metrics.precision_score(test_y,test_predictions) #精确率
print (\"Test Auc: %.2f%%\" % (test_auc * 100.0))
print (\"Test Accuary: %.2f%%\" % (test_accuracy * 100.0))
print (\"Test Recall: %.2f%%\" % (test_recall * 100.0))
print (\"Test Precision: %.2f%%\" % (test_precision * 100.0))
print (\"Test F1: %.2f%%\" % (test_f1 * 100.0))
fpr,tpr,threshold = metrics.roc_curve(test_y,test_preds)
pyplot.plot(fpr, tpr, color=\'blue\',lw=2, label=\'ROC curve (area = %.2f%%)\' % (test_auc * 100.0)) ###假正率为横坐标,真正率为纵坐标做曲线
pyplot.legend(loc=\"lower right\")
pyplot.plot([0, 1], [0, 1], color=\'navy\', lw=lw, linestyle=\'--\')
pyplot.xlabel(\'False Positive Rate\')
pyplot.ylabel(\'True Positive Rate\')
pyplot.title(\'ROC curve\')
#Test Auc: 81.99%
#Test Accuary: 81.44%
#Test Recall: 36.55%
#Test Precision: 56.25%
#Test F1: 44.31%