梯度提升&随机森林混杂算法预测红酒口感

使用sklearn包实现底层二叉决策树随机森林生成,迭代过程使用梯度提升法,最后结果bagging投票决定,下面是算法实现过程:

# -*- coding:utf-8 -*-
import urllib.request
import numpy
from sklearn.model_selection import train_test_split
from sklearn import ensemble
from sklearn.metrics import mean_squared_error
import pylab as plot

#从网页中读取数据
url="http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv"
data=urllib.request.urlopen(url)

#将数据中第一行的属性读取出来放在names列表中,将其他行的数组读入row中,并将row中最后一列提取
#出来放在labels中作为标签,并使用pop将该列从row去去除掉,最后将剩下的属性值转化为float类型存入xList中
xlist=[]
labels=[]
names=[]
firstline=True
for line in data:
    if firstline:
        names=line.strip().split(b';')
        firstline=False
    else:
        row=line.strip().split(b';')
        labels.append(float(row[-1]))
        row.pop()
        floatrow=[float(num) for num in row]
        xlist.append(floatrow)

#计算几行几列
nrows=len(xlist)
ncols=len(xlist[1])

#转化为numpy格式
x=numpy.array(xlist)
y=numpy.array(labels)
winenames=numpy.array(names)

#随机抽30%的数据用于测试,随机种子为531固定值,确保多次运行结果相同便于优化算法
xtrain,xtest,ytrain,ytest=train_test_split(x,y,test_size=0.30,random_state=531)

#初始化训练梯度模型的各种参数(根据效果微调)
#树的个数
nest=2000
#树的深度
depth=7
#梯度下降系数
learnrate=0.01
#0.5混杂随机选择属性,与随机森林算法结合
subsamp=0.5

#训练随机森林与梯度提升算法混杂的模型
winerandomforestmodel=ensemble.GradientBoostingRegressor(n_estimators=nest,max_depth=depth,learning_rate=learnrate,subsample=subsamp,loss='ls')
winerandomforestmodel.fit(xtrain,ytrain)

#迭代预测,方差加入mserror列表
mserror=[]
predictions=winerandomforestmodel.staged_predict(xtest)
for p in predictions:
    mserror.append(mean_squared_error(ytest,p))

print("MSE")
print(min(mserror))
print(mserror.index(min(mserror)))

#plot.figure:绘制多个图像
plot.figure()
plot.plot(range(1,nest+1),winerandomforestmodel.train_score_,label='training set mse')
plot.plot(range(1,nest+1),mserror,label='test set mse')
#图列
plot.legend(loc='upper right')
plot.xlabel('number of trees in ensemble')
plot.ylabel('mean squared error')
plot.show()

算法需要对具体参数进行微调来提升效率和降低均方差
1.
nest=2000
depth=7
learnrate=0.02~0.1 #多次测试
subsamp=1.0

结果:MSE
0.346210798243
需要:54棵树

测试数据迅速下降然后迅速上升,说明梯度太大了
2.
nest=2000
depth=7
learnrate=0.01
subsamp=1.0 #不使用随机森林生成底层二叉决策树

结果:MSE
0.341110096535
需要:1306棵树

更高的均方差,更多的决策树

3.
nest=2000
depth=7
learnrate=0.01
subsamp=0.5

结果:MSE
0.323308044245
需要:873棵树

4.
depth多少比较好
1:0.401720241762******1738
2:0.373627903865******1800
3:0.349706370241******1993
4:0.337589219137******1435
5:0.327691820722******1301
6:0.320751183951******924
7:0.321455606096******883
8:0.305907145681******815

!!!6/7比较好,说明各个参数之间联系比较大

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值