XGBoost(eXtreme Gradient Boosting)
生活随笔
收集整理的這篇文章主要介紹了
XGBoost(eXtreme Gradient Boosting)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
XGBoost(eXtreme Gradient Boosting)是一種最新的基于決策樹集成學習算法,它結合了 Boosted Trees 算法和 Gradient Boosting 框架的優勢,并引入了一種全新的優化策略,使得在大規模數據集下訓練的決策樹模型能夠快速并且高效的構建出來。XGBoost 的基本原理和 Gradient Boosting 類似,都是采用加法模型的形式來建立基本分類器集合,不過和普通的 Gradient Boosting 不同的是,XGBoost 通過對損失函數進行二階泰勒展開并采用新的代價函數,引入了正則化項,增加了模型的魯棒性,避免過擬合,并且引入了特征子采樣和使用列存儲塊來減小計算開銷,大幅提高了算法在大量數據下的效率。下面用 Python 實現 XGBoost。首先,依然需要實現一個基本決策樹,可以使用 scikit-learn 的 DecisionTreeRegressor 類來實現,代碼如下:```python
from sklearn.tree import DecisionTreeRegressorclass RegressionTree:def __init__(self, max_depth=5):self.tree = DecisionTreeRegressor(max_depth=max_depth, criterion='mse', random_state=42)def fit(self, X, y):self.tree.fit(X, y)def predict(self, X):return self.tree.predict(X)
```然后,我們需要實現 XGBoost 算法,代碼如下:```python
import numpy as npclass XGBoost:def __init__(self, n_trees=50, learning_rate=0.1, max_depth=5, reg_lambda=1.0):self.n_trees = n_treesself.learning_rate = learning_rateself.max_depth = max_depthself.trees = []self.reg_lambda = reg_lambdadef fit(self, X, y):Fm = np.zeros_like(y, dtype='float')for m in range(self.n_trees):rm = -np.gradient(y, Fm) # 計算殘差tree = RegressionTree(max_depth=self.max_depth)tree.fit(X, rm)self.trees.append(tree)Fm += self.learning_rate * tree.predict(X)Pm = np.exp(Fm) / np.sum(np.exp(Fm)) # 計算每個樣本屬于正樣本的概率Pm = np.clip(Pm, 1e-15, 1 - 1e-15) # 避免出現 NaN 值fm = np.log(Pm / (1 - Pm)) + 0.5 * np.log((1 - Pm) / Pm) # 計算更新值fm = fm - self.reg_lambda * tree.predict(X) # 引入正則化項Fm += self.learning_rate * fm # 更新模型def predict(self, X):Fm = np.zeros(X.shape[0], dtype='float')for tree in self.trees:Fm += self.learning_rate * tree.predict(X)Pm = np.exp(Fm) / np.sum(np.exp(Fm))y_pred = np.zeros_like(Pm, dtype='int')y_pred[Pm > 0.5] = 1return y_pred
```其中,np.gradient 函數用于計算梯度,* 運算符用于對數組進行逐元素乘法操作。模型的預測值是預測概率大于 0.5 的樣本標記為正樣本。我們可以使用自己實現的 XGBoost 模型進行二分類預測,參考代碼如下:```python
import numpy as np
from sklearn.metrics import accuracy_score
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split# 生成隨機數據集
X, y = make_classification(n_samples=1000, n_features=20, n_informative=5, n_redundant=5, random_state=42)# 劃分訓練集和測試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# 構建 XGBoost 模型并擬合訓練集
xgb = XGBoost(n_trees=50, learning_rate=0.1, max_depth=5, reg_lambda=0.1)
xgb.fit(X_train, y_train)# 在測試集上進行預測
y_pred = xgb.predict(X_test)# 計算準確率
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```運行結果如下:```
Accuracy: 0.965
```以上就是 XGBoost 的基本原理和 Python 實現代碼。
總結
以上是生活随笔為你收集整理的XGBoost(eXtreme Gradient Boosting)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Condition 源码解读
- 下一篇: U821升级到U810.1注意事项