首頁(yè) 資訊 梯度提升回歸

梯度提升回歸

來源:泰然健康網(wǎng) 時(shí)間:2024年12月13日 06:06

此示例演示了梯度提升從一組弱預(yù)測(cè)模型生成預(yù)測(cè)模型。梯度提升可以用于回歸和分類問題。在這里,我們將訓(xùn)練一個(gè)模型來處理糖尿病回歸任務(wù)。我們將從梯度提升回歸器中得到結(jié)果, 這個(gè)梯度提升回歸器是使用最小二乘損失, 和500課深度為4的回歸樹組成。

注:對(duì)于較大的數(shù)據(jù)集(n_samples >= 10000),請(qǐng)參閱sklearn.ensemble.HistGradientBoostingRegressor。

print(__doc__)

# Author: Peter Prettenhofer <peter.prettenhofer@gmail.com>
#         Maria Telenczuk <https://github.com/maikia>
#         Katrina Ni <https://github.com/nilichen>
#
# License: BSD 3 clause

import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, ensemble
from sklearn.inspection import permutation_importance
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split

加載數(shù)據(jù)

首先,我們需要加載數(shù)據(jù)。

diabetes = datasets.load_diabetes()
X, y = diabetes.data, diabetes.target

數(shù)據(jù)預(yù)處理

接下來,我們將我們的數(shù)據(jù)集分割成90%用于訓(xùn)練,剩下的用作測(cè)試。我們還將設(shè)置回歸模型的參數(shù)。您可以使用這些參數(shù)查看結(jié)果如何變化。

n_estimators :將執(zhí)行的提升次數(shù)。稍后,我們將繪制反提升迭代的偏差。

max_depth :限制樹中的節(jié)點(diǎn)數(shù)。最佳的值取決于輸入變量之間的相互作用。

min_samples_split :內(nèi)部節(jié)點(diǎn)分割時(shí)所需的最小樣本數(shù)。

learning_rate :每棵樹的貢獻(xiàn)會(huì)減少多少。

loss :損失函數(shù)優(yōu)化。在這種情況下,使用最小二乘函數(shù),但是還有許多其他選項(xiàng)。(看GradientBoostingRegressor)。

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.1, random_state=13)

params = {'n_estimators': 500,
          'max_depth': 4,
          'min_samples_split': 5,
          'learning_rate': 0.01,
          'loss': 'ls'}

擬合回歸模型

現(xiàn)在,我們將初始化一個(gè)梯度提升回歸器,并將其與我們的訓(xùn)練數(shù)據(jù)進(jìn)行擬合。讓我們也看看測(cè)試數(shù)據(jù)的均方誤差。

reg = ensemble.GradientBoostingRegressor(**params)
reg.fit(X_train, y_train)

mse = mean_squared_error(y_test, reg.predict(X_test))
print("The mean squared error (MSE) on test set: {:.4f}".format(mse))

The mean squared error (MSE) on test set: 3017.9419

繪制訓(xùn)練偏差

最后,我們將可視化結(jié)果。要做到這一點(diǎn),我們將首先計(jì)算測(cè)試集偏差,然后根據(jù)提升迭代繪制測(cè)試集偏差圖。

test_score = np.zeros((params['n_estimators'],), dtype=np.float64)
for i, y_pred in enumerate(reg.staged_predict(X_test)):
    test_score[i] = reg.loss_(y_test, y_pred)

fig = plt.figure(figsize=(6, 6))
plt.subplot(1, 1, 1)
plt.title('Deviance')
plt.plot(np.arange(params['n_estimators']) + 1, reg.train_score_, 'b-',
         label='Training Set Deviance')
plt.plot(np.arange(params['n_estimators']) + 1, test_score, 'r-',
         label='Test Set Deviance')
plt.legend(loc='upper right')
plt.xlabel('Boosting Iterations')
plt.ylabel('Deviance')
fig.tight_layout()
plt.show()

繪制特征重要性

小心一點(diǎn)、基于不純度的特征重要性對(duì)于高基數(shù)的特征(許多唯一的值)可能會(huì)產(chǎn)生誤導(dǎo)。作為一個(gè)替代項(xiàng),reg的排列重要性可以在一個(gè)保持的測(cè)試集上計(jì)算??碢ermutation feature importance更多細(xì)節(jié)。

在本例中,基于不純度和排列方法識(shí)別相同的2個(gè)強(qiáng)預(yù)測(cè)特征,但順序不同。第三大預(yù)測(cè)特征,“bp”,在這兩種方法中也是相同的。其余特征的預(yù)測(cè)性較低,排列圖中的錯(cuò)誤條顯示它們與0重疊。

feature_importance = reg.feature_importances_
sorted_idx = np.argsort(feature_importance)
pos = np.arange(sorted_idx.shape[0]) + .5
fig = plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.barh(pos, feature_importance[sorted_idx], align='center')
plt.yticks(pos, np.array(diabetes.feature_names)[sorted_idx])
plt.title('Feature Importance (MDI)')

result = permutation_importance(reg, X_test, y_test, n_repeats=10,
                                random_state=42, n_jobs=2)
sorted_idx = result.importances_mean.argsort()
plt.subplot(1, 2, 2)
plt.boxplot(result.importances[sorted_idx].T,
            vert=False, labels=np.array(diabetes.feature_names)[sorted_idx])
plt.title("Permutation Importance (test set)")
fig.tight_layout()
plt.show()

腳本的總運(yùn)行時(shí)間:(0分2.168秒)

Download Python source code:plot_gradient_boosting_regression.py

Download Jupyter notebook:plot_gradient_boosting_regression.ipynb

相關(guān)知識(shí)

電梯房朝向哪個(gè)方向好,提升居住舒適度的關(guān)鍵
提升鎮(zhèn)痛率?讓產(chǎn)婦回歸自然分娩
來回上下樓梯能減肥嗎
提升心肺耐力的秘密武器:爬樓梯訓(xùn)練在日常鍛煉中的作用
回歸自然,健康養(yǎng)生這么做
勇者回歸豪禮相送 4月22日更新公告
Isha瑜伽:回歸純粹的古典瑜伽科學(xué)
爬樓梯的減肥效果強(qiáng)嗎?每天爬100層樓梯是不是可行?
醫(yī)美消費(fèi)應(yīng)回歸理性
居家康復(fù)服務(wù),助力患者回歸家庭回歸社會(huì) 新聞動(dòng)態(tài)

網(wǎng)址: 梯度提升回歸 http://www.u1s5d6.cn/newsview484937.html

推薦資訊