1. 程式人生 > 其它 >資料探勘演算法和實踐(二十三):XGBoost整合演算法案列(鳶尾花資料集)

資料探勘演算法和實踐(二十三):XGBoost整合演算法案列(鳶尾花資料集)

技術標籤:機器學習/資料探勘實戰python機器學習深度學習人工智慧演算法

本節繼續探討整合學習演算法,上一節介紹的是LGB的使用和調參,這裡使用datasets自帶的鳶尾花資料集介紹XGB,關於整合學習演算法的介紹可以參考:資料探勘演算法和實踐(十八):整合學習演算法(Boosting、Bagging),XGB和LGB都是競賽和真實場景用得很多的演算法,這裡詳細分析XGB調參和特徵選擇;

一、引包與載入資料

import time
import numpy as np
import xgboost as xgb
from xgboost import plot_importance,plot_tree
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.datasets import load_boston
import matplotlib
import matplotlib.pyplot as plt
import os
%matplotlib inline

# 載入樣本資料集
iris = load_iris()
X,y = iris.data,iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1234565) # 資料集分割

二、建模和引數

# 訓練演算法引數設定
params = {
    # 通用引數
    'booster': 'gbtree', # 使用的弱學習器,有兩種選擇gbtree(預設)和gblinear,gbtree是基於
                        # 樹模型的提升計算,gblinear是基於線性模型的提升計算
    'nthread': 4, # XGBoost執行時的執行緒數,預設時是當前系統獲得的最大執行緒數
    'silent':0, # 0:表示列印執行時資訊,1:表示以緘默方式執行,預設為0
    'num_feature':4, # boosting過程中使用的特徵維數
    'seed': 1000, # 隨機數種子
    # 任務引數
    'objective': 'multi:softmax', # 多分類的softmax,objective用來定義學習任務及相應的損失函式
    'num_class': 3, # 類別總數
    # 提升引數
    'gamma': 0.1, # 葉子節點進行劃分時需要損失函式減少的最小值
    'max_depth': 6, # 樹的最大深度,預設值為6,可設定其他值
    'lambda': 2, # 正則化權重
    'subsample': 0.7, # 訓練模型的樣本佔總樣本的比例,用於防止過擬合
    'colsample_bytree': 0.7, # 建立樹時對特徵進行取樣的比例
    'min_child_weight': 3, # 葉子節點繼續劃分的最小的樣本權重和
    'eta': 0.1, # 加法模型中使用的收縮步長   
    
}
plst = params.items()


# 資料集格式轉換
dtrain = xgb.DMatrix(X_train, y_train)
dtest = xgb.DMatrix(X_test)

# 迭代次數,對於分類問題,每個類別的迭代次數,所以總的基學習器的個數 = 迭代次數*類別個數
num_rounds = 50
model = xgb.train(plst, dtrain, num_rounds) # xgboost模型訓練

# 對測試集進行預測
y_pred = model.predict(dtest)

# 計算準確率
accuracy = accuracy_score(y_test,y_pred)
print("accuarcy: %.2f%%" % (accuracy*100.0))

# 顯示重要特徵
plot_importance(model)
plt.show()

三、模型評估

# 視覺化樹的生成情況,num_trees是樹的索引
plot_tree(model, num_trees=5) 

# 將基學習器輸出到txt檔案中
model.dump_model("model1.txt")

XGB的迴歸問題

# 載入資料集
boston = load_boston()
# 獲取特徵值和目標指
X,y = boston.data,boston.target
# 獲取特徵名稱
feature_name = boston.feature_names

# 劃分資料集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

# 引數設定
params = {
        'booster': 'gbtree',
        'objective': 'reg:gamma', # 迴歸的損失函式,gmma迴歸
        'gamma': 0.1,
        'max_depth': 5,
        'lambda': 3,
        'subsample': 0.7,
        'colsample_bytree': 0.7,
        'min_child_weight': 3,
        'silent': 1,
        'eta': 0.1,
        'seed': 1000,
        'nthread': 4,
    }
plst = params.items()


# 資料集格式轉換
dtrain = xgb.DMatrix(X_train, y_train,feature_names = feature_name)
dtest = xgb.DMatrix(X_test,feature_names = feature_name)

# 模型訓練
num_rounds = 30
model = xgb.train(plst, dtrain, num_rounds)

# 模型預測
y_pred = model.predict(dtest)

# 顯示重要特徵
plot_importance(model,importance_type ="weight")
plt.show()

# 視覺化樹的生成情況,num_trees是樹的索引
plot_tree(model, num_trees=17) 

# 將基學習器輸出到txt檔案中
model.dump_model("model2.txt")