xgboost既可以通過自己本身的接口進行訓練,也可以藉助sklearn的接口訓練,下面一一進行介紹。
代碼如下所示
# _*_ coding: UTF-8 _*_
from sklearn.datasets import load_iris
import xgboost as xgb
from xgboost import plot_importance
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
# 加載數據
# data = np.random.rand(5,10)
# label = np.random.randint(2, size=5)
# dtrain = xgb.DMatrix(data, label=label)
iris = load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=1234565)
# 參數設置
params = {
'booster': 'gbtree',
'objective': 'multi:softmax', # 多分類的問題
'num_class': 3, # 類別數,與 multisoftmax 並用
'gamma': 0.1, # 用於控制是否後剪枝的參數,越大越保守,一般0.1、0.2這樣子。
'max_depth': 6, # 構建樹的深度,越大越容易過擬合
'lambda': 2, # 控制模型複雜度的權重值的L2正則化項參數,參數越大,模型越不容易過擬合。
'subsample': 0.7, # 隨機採樣訓練樣本
'colsample_bytree': 0.7, # 生成樹時進行的列採樣
'min_child_weight': 3,
'silent': 1, # 設置成1則沒有運行信息輸出,最好是設置爲0.
'eta': 0.1, # 如同學習率
'seed': 1000,
'nthread': 4, # cpu 線程數
}
# xgb矩陣賦值
xgb_train = xgb.DMatrix(X_train, label=y_train)
xgb_test = xgb.DMatrix(X_test, label=y_test)
# 訓練模型
plst = list(params.items())
watchlist = [(xgb_train, 'train'), (xgb_test, 'val')]
num_round = 500
model = xgb.train(plst, xgb_train, num_round, watchlist)
# 評價訓練模型
y_pred = model.predict(xgb_test, ntree_limit=model.best_ntree_limit)
# 計算準確率
cnt1 = 0
cnt2 = 0
for i in range(len(y_test)):
if y_pred[i] == y_test[i]:
cnt1 += 1
else:
cnt2 += 1
print("Accuracy: %.2f %% " % (100 * cnt1 / (cnt1 + cnt2)))
# 顯示重要特徵
plot_importance(model)
plt.show()
得到的結果如下:
從上圖中可以看到特徵的重要性,其中f2特徵被分裂了139次。
上圖得到了所訓練的分類器的精確度。
通過控制檯看變量,可以看到訓練得到的model的最佳迭代次數是499以及其他信息。
之前由於無法導入graphviz模塊,因此只繪製了重要性,而沒有繪製樹,這裏我找到了解決辦法,見博文
解決Aanaconda3 安裝 graphviz但是在pycharm裏面無法調用的問題
在上面的代碼後加上兩行畫決策樹的代碼,可以得到下面的圖。
xgb.plot_tree(model, num_trees=10) # 因爲缺少pygraphviz-1.3.1-cp36-none-win32的模塊 所以並不能畫圖,後來解決了
plt.show()
代碼如下所示
# _*_ coding: UTF-8 _*_
from sklearn.datasets import load_iris
import xgboost as xgb
from xgboost.sklearn import XGBClassifier # sklearn接口
from xgboost import plot_importance
from matplotlib import pyplot as plt
import graphviz
from sklearn.model_selection import train_test_split
# 加載數據
iris = load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# 訓練模型
model = XGBClassifier(max_depth=5, learning_rate=0.1, n_estimators=160, silent=True, objective='multi:softmax')
model.fit(X_train, y_train)
# 評價訓練模型
y_pred = model.predict(X_test)
# 計算準確率
cnt1 = 0
cnt2 = 0
for i in range(len(y_test)):
if y_pred[i] == y_test[i]:
cnt1 += 1
else:
cnt2 += 1
print("Accuracy: %.2f %% " % (100 * cnt1 / (cnt1 + cnt2)))
# 顯示重要特徵
plot_importance(model)
plt.show()
xgb.plot_tree(model, num_trees=10)
plt.show()
得到的結果如下圖所示:
其中精確度達到了。