Python實現GBDT(參數介紹;調用;調參)

GBDT(Gradient Boosting Decision Tree),每一次建立樹模型是在之前建立模型損失函數的梯度下降方向,即利用了損失函數的負梯度在當前模型的值作爲迴歸問題提升樹算法的殘差近似值,去擬合一個迴歸樹。GBDT應用有迴歸和分類:GBDT分類每一顆樹擬合當前整個模型的損失函數的負梯度,構建新的樹加到當前模型中形成新模型,下一棵樹擬合新模型的損失函數的負梯度;GBDT迴歸每一顆樹擬合當前整個模型的殘差,構建新的樹加到當前模型中形成新模型,下一棵樹擬合新模型的損失函數的負梯度。

下面是其在Python的sklearn包下簡單調用方法:

import pandas as pd
from sklearn.model_selection import train_test_split


filePath01 = r'F://temp_data/train_V2.csv'
data01 = pd.read_csv(filePath01)
data01.head()  # 讀取前五行數據,如果是最後五行,用data.tail()
print(data01.shape)  # 看數據的維度
X = data01.drop(['rank'], axis=1)
y = data01[:, ['rank']]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=2333)

from sklearn import ensemble
clf = ensemble.GradientBoostingClassifier()
gbdt_model = clf.fit(X_train, y_train)  # Training model
y_predict = gbdt_model.predict_proba(X_test)[:, 1]  # predict: probablity of 1


from sklearn import ensemble
clf = ensemble.GradientBoostingRegressor(n_estimators=100,
                                         max_depth=3,
                                         loss='ls')
gbdt_model = clf.fit(X_train, y_train)  # Training model
y_upper = gbdt_model.predict(X_test)  # predict
'''
boosting框架參數:
n_estimators:學習器的最大迭代次數,迴歸樹的數量
max_depth:每棵獨立樹的深度
loss:GBDT的損失函數,分類模型和迴歸模型的損失函數不一樣的,(ls爲最小二乘函數,用於迴歸)
learning_rate:學習速率,較低的學習速率需要更高數量的n_estimators,以達到相同程度的訓練集誤差–用時間換準確度的。
subsample:(0,1],子採樣。隨機森林是有放回的採樣,這裏是不放回的採樣

CART迴歸樹學習器的參數:
max_features:劃分時考慮的最大特徵數
max_depth:決策樹的最大深度
min_samples_split:限制子樹繼續劃分的條件,如果某結點的樣本數少於它,就不會再繼續劃分
min_samples_leaf:限制葉子節點最少的樣本數,如果某葉子節點數目小於樣本數,則會和兄弟結點一起被減掉
max_laef_nodes:最大葉子結點數,防止過擬合


'''
# 調參小技巧
# 根據要解決的問題選擇損失函數
# n_estimators儘可能大(如3000)
# 通過grid search方法對max_depth, learning_rate, min_samples_leaf, 及max_features進行尋優
# 增加n_estimators,保持其它參數不變,再次對learning_rate調優


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章