sklearn Gradient Tree Boosting

这篇博客介绍了如何利用sklearn库中的GradientTreeBoosting方法进行机器学习,特别是通过一个例子展示了如何训练和评估模型,计算均方误差,并利用可视化展示特征重要性和提升迭代过程中的Deviance变化。
摘要由CSDN通过智能技术生成
sklearn.metrics.mean_squared_error:
标准均方误。
Gradient Tree Boosting方法可以看作将AdaBoost方法的模型组合方式应用于决策树,
但并不采取单点迭代惩罚加权,而是对某个模型采用对所有样本的距离模式(l2 l1 and so on)
来求解。

在GTB中设计后的模型中调用loss_可以返回使用的损失函数,可以用来计算单步损失。
调用feature_importance_可以返回模型的特征重要度量。

plt.barh用于绘制条形图。

下面是一个例子:
import numpy as np 
import matplotlib.pyplot as plt 

from sklearn import ensemble 
from sklearn import datasets 
from sklearn.utils import shuffle 
from sklearn.metrics import mean_squared_error 

boston = datasets.load_boston()
X, y = shuffle(boston.data, boston.target, random_state = 13)
X = X.astype(np.float32)
offset = int(X.shape[0] * 0.9)
X_train, y_train = X[:offset], y[:offset]
X_test, y_test = X[offset:], y[offset:]

params = {'n_estimators': 500, 'max_depth': 4, 'min_samples_split': 1, 'learning_rate': 0.01, 'loss': 'ls'}
clf = ensemble.GradientBoostingRegressor(**params)
clf.fit(X_train, y_train)

mse = mean_squared_error(y_test, clf.predict(X_test))
print "MSE: %.4f" % mse 

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

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

feature_importance = clf.feature_importances_
feature_importance = 100.0 * (feature_importance / feature_importance.max())
sorted_idx = np.argsort(feature_importance)
pos = np.arange(sorted_idx.shape[0]) + .5
plt.subplot(1, 2, 2)
plt.barh(pos, feature_importance[sorted_idx], align = 'center')
plt.yticks(pos, boston.feature_names[sorted_idx])
plt.xlabel("Relative Importance")
plt.title("Variance Importance")
plt.show()



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值