交叉验证获得最佳二元决策树深度

10折交叉验证各个深度下的平均误差然后看看哪个深度会对预测产生明显的优势

# -*- coding:utf-8 -*-
import numpy
import matplotlib.pyplot as plot
from sklearn import tree
from sklearn.tree import DecisionTreeRegressor
from sklearn.externals.six import StringIO

#构造简单的数据y=x+random
npoints=100

#使x在-0.5和0.5之间共100份
xplot=[(float(i)/float(npoints)-0.5) for i in range(npoints+1)]

#多行变多列
x=[[s] for s in xplot]

#生成随机数并生成y=x+random
numpy.random.seed(1)
y=[s+numpy.random.normal(scale=0.1) for s in xplot]

nrow=len(x)
depthlist=[1,2,3,4,5,6,7]
xvalmse=[]
nxval=10

#使用各个深度数据循环尝试
for idepth in depthlist:
    #确定深度数据后分块交叉验证循环
    for ixval in range(nxval):
        #分割数据
        itest=[a for a in range(nrow) if a%nxval==ixval]
        itrain=[a for a in range(nrow) if a%nxval!=ixval]

        xtrain=[x[r] for r in itrain]
        xtest=[x[r] for r in itest]
        ytrain=[y[r] for r in itrain]
        ytest=[y[r] for r in itest]

        #训练
        treemodel=DecisionTreeRegressor(max_depth=idepth)
        treemodel.fit(xtrain,ytrain)

        #预测
        treeprediction=treemodel.predict(xtest)

        #算误差
        error=[ytest[r]-treeprediction[r] for r in range(len(xtest))]

        if ixval==0:
            ooserrors=sum([e*e for e in error])
        else:
            ooserrors+=sum([e*e for e in error])
    xvalmse.append(ooserrors/nrow)

plot.plot(depthlist,xvalmse)
plot.axis('tight')
plot.xlabel('depth')
plot.ylabel('mse')
plot.show()

100个样本下3层深度最优
这里写图片描述

1000个样本下4层更好
这里写图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值