前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >XGBoost(三):Python语言实现

XGBoost(三):Python语言实现

作者头像
三猫
发布2020-03-24 10:26:59
8270
发布2020-03-24 10:26:59
举报

戳蓝色字关注我们哟!

上篇文章介绍了XGBoost在R语言中的实现方法(XGBoost(二):R语言实现),本篇文章接着来介绍XGBoost在Python中的实现方法。

1

XGBoost库

Python中,可直接通过“pip install xgboost”安装XGBoost库,基分类器支持决策树和线性分类器。

2

XGBoost代码实现

本例中我们使用uci上的酒质量评价数据,该数据通过酸性、ph值、酒精度等11个维度对酒的品质进行评价,对酒的评分为0-10分。

  • 相关库载入 除了xgboost,本例中我们还将用到pandas、sklearn和matplotlib方便数据的读入、处理和最后的图像绘制。
代码语言:javascript
复制
import xgboost
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import metrics
from xgboost import plot_importance
from matplotlib import pyplot
  • 数据加载 将数据导入Python,并对数据根据7:3的比例划分为训练集和测试集,并对label进行处理,超过6分为1,否则为0。
代码语言:javascript
复制
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] = 0
y[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类型。
代码语言:javascript
复制
dtrain = xgboost.DMatrix(data = train_x, label = train_y)
dtest = xgboost.DMatrix(data = test_x, label = test_y)
  • 模型训练 训练模型,并对特征进行重要性排序。
代码语言:javascript
复制
param = {'max_depth':6, 'eta':0.5, 'silent':0, 'objective':'binary:logistic' }
num_round = 2
xgb = 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曲线图。
代码语言:javascript
复制
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%

后台回复“xgbPy”获得完整代码

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-03-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 机器学习养成记 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档