原文鏈接:XGBoost(三):Python語言實現(xiàn)
微信公眾號:機器學(xué)習(xí)養(yǎng)成記
上篇文章介紹了XGBoost在R語言中的實現(xiàn)方法(XGBoost(二):R語言實現(xiàn))杈帐,本篇文章接著來介紹XGBoost在Python中的實現(xiàn)方法劲阎。
1匠题、XGBoost庫
Python中颜懊,可直接通過“pip install xgboost”安裝XGBoost庫融欧,基分類器支持決策樹和線性分類器同规。
2旷坦、XGBoost代碼實現(xiàn)
本例中我們使用uci上的酒質(zhì)量評價數(shù)據(jù),該數(shù)據(jù)通過酸性搀崭、ph值、酒精度等11個維度對酒的品質(zhì)進行評價猾编,對酒的評分為0-10分瘤睹。
相關(guān)庫載入
除了xgboost,本例中我們還將用到pandas答倡、sklearn和matplotlib方便數(shù)據(jù)的讀入轰传、處理和最后的圖像繪制。
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
數(shù)據(jù)加載
將數(shù)據(jù)導(dǎo)入Python瘪撇,并對數(shù)據(jù)根據(jù)7:3的比例劃分為訓(xùn)練集和測試集获茬,并對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] = 0
y[y>6] =1
# test_size: 測試集大小
# random_state: 設(shè)置隨機數(shù)種子鹏氧,0或不填則每次劃分結(jié)果不同
train_x,test_x,train_y,test_y = train_test_split(x,y,test_size=0.3, random_state=17)
數(shù)據(jù)預(yù)處理
將數(shù)據(jù)轉(zhuǎn)化為xgb.DMatrix類型。
dtrain= xgboost.DMatrix(data = train_x, label = train_y)
dtest= xgboost.DMatrix(data = test_x, label = test_y)
模型訓(xùn)練
訓(xùn)練模型佩谣,并對特征進行重要性排序把还。
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)#打印重要程度結(jié)果
pyplot.show()
測試集效果檢驗
計算準(zhǔn)確率茸俭、召回率等指標(biāo)吊履,并繪制ROC曲線圖。
test_accuracy = metrics.accuracy_score(test_y, test_predictions)#準(zhǔn)確率
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))###假正率為橫坐標(biāo)调鬓,真正率為縱坐標(biāo)做曲線
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%
公眾號后臺回復(fù)“xgbPy”獲得完整代碼
原文鏈接:XGBoost(三):Python語言實現(xiàn)
微信公眾號:機器學(xué)習(xí)養(yǎng)成記