会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132846个问题
Python 全系列/ 第十三阶段:自动化操作办公软件、邮件、定时任务等/自动化操作办公软件、邮件、定时任务等 18514楼
JAVA 全系列/第六阶段:项目管理与SSM框架/SpringMVC 18515楼
JAVA 全系列/第六阶段:项目管理与SSM框架/SpringMVC 18516楼
JAVA 全系列/第二十一阶段:Spring Cloud Alibaba技术栈/Seata 18518楼
JAVA 全系列/第六阶段:项目管理与SSM框架/RBAC实战 18520楼
JAVA 全系列/第六阶段:项目管理与SSM框架/Mybatis 18521楼
JAVA 全系列/第一阶段:JAVA 快速入门/数组和数据存储 18522楼

import numpy as np
from sklearn.tree import DecisionTreeRegressor
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score

N = 100
x = np.random.rand(N) * 6 - 3   
y = np.sin(x) + np.random.rand(N) * 0.05
# print(y)

#将x转化成一列
x = x.reshape(-1, 1)
# print(x)

dt_reg = DecisionTreeRegressor(criterion='mse', max_depth=3)
dt_reg.fit(x, y)

x_test = np.linspace(-3, 3, 50).reshape(-1,1) 
y_hat = dt_reg.predict(x_test)


plt.plot(x, y, 'y*', label="actual")  
plt.plot(x_test, y_hat, "b-", linewidth=2, label='predict')
plt.legend(loc='upper left')
plt.grid()
# plt.savefig("./temp_decision_tree_regressor")
plt.show()   #必须先保存,再展示

#比较不同深度的决策树
depth = [2, 4, 6, 8, 10]
color='rgbmy'
dt_reg = DecisionTreeRegressor(criterion="mse")   #默认criterion="mse",
plt.plot(x, y, 'ko', label="actual")
x_test = np.linspace(-3, 3, 50).reshape(-1, 1)
y_test = np.sin(x_test) + np.random.rand(N) * 0.05
print(y_test)
for d, c in zip(depth, color):
    dt_reg.set_params(max_depth=d)  #设置超参数
    dt_reg.fit(x, y)
    y_hat = dt_reg.predict(x_test)
    plt.plot(x_test, y_hat, '-', color=c, linewidth=2, label='depth=%d' % d)
    acc_score = accuracy_score(y_test, y_hat)
    print("depth:",d)
    print('acc score:',acc_score)

plt.legend(loc='upper left')
plt.grid(b=True)
plt.savefig("./temp_compare_decision_tree_regressor")
plt.show()

老师,请问, 这里想测试max_depth为多少的时候会过拟合,加了这三行代码,报错了,不知道哪里不对

image.png

image.png

Python 全系列/第二十三阶段:人工智能基础_机器学习理论和实战(旧)/决策树算法 18524楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637