决策树回归"/>
多输出决策树回归
原文以及代码来自于下面链接,本人对每段代码进行了详细注释,希望对初学者有用。非常建议用pycharm的调试模式,可以查看每个数据的内容。
.html#sphx-glr-auto-examples-tree-plot-tree-regression-multioutput-py
一个示例,用于用决策树说明多输出回归。
决策树用于同时预测给定单个基础要素的圆的噪声 x 和 y 观测值。因此,它学习接近圆的局部线性回归。
我们可以看到,如果树的最大深度(由最大深度参数控制)设置得过高,则决策树会学习训练数据的细节,并从噪声中学习,即它们过度拟合。
print(__doc__)import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeRegressor# Create a random dataset
rng = np.random.RandomState(1)
X = np.sort(200 * rng.rand(100, 1) - 100, axis=0)
y = np.array([np.pi * np.sin(X).ravel(), np.pi * np.cos(X).ravel()]).T
y[::5, :] += (0.5 - rng.rand(20, 2))
'''
numpy.random.RandomState()是一个伪随机数生成器。那么伪随机数是什么呢? ()括号内是seed,确保不同电脑上产生相同的伪随机数
伪随机数是用确定性的算法计算出来的似来自[0,1]均匀分布的随机数序列。并不真正的随机,但具有类似于随机数的统计特征,如均匀性、独立性等。
运行一下下面两个
rng = np.random.RandomState(1)
x = rng.rand(4)
y = rng.rand(4)
rng = np.random.RandomState(1)
x = rng.rand(4)
rng = np.random.RandomState(1)
y = rng.rand(4).sort axis =0 每列从小到大排列.ravel() 将多维数组降位一维y[::5] 从开始到结束,每隔5个数,第0个开始取出算起,更加详细的取数组元素方式可以参看下面链接
'''# Fit regression model
regr_1 = DecisionTreeRegressor(max_depth=2)
regr_2 = DecisionTreeRegressor(max_depth=5)
regr_3 = DecisionTreeRegressor(max_depth=8)
regr_1.fit(X, y)
regr_2.fit(X, y)
regr_3.fit(X, y)# Predict
X_test = np.arange(-100.0, 100.0, 0.01)[:, np.newaxis]
y_1 = regr_1.predict(X_test)
y_2 = regr_2.predict(X_test)
y_3 = regr_3.predict(X_test)# Plot the results
plt.figure()
s = 25
plt.scatter(y[:, 0], y[:, 1], c="navy", s=s,edgecolor="black", label="data")
plt.scatter(y_1[:, 0], y_1[:, 1], c="cornflowerblue", s=s,edgecolor="black", label="max_depth=2")
plt.scatter(y_2[:, 0], y_2[:, 1], c="red", s=s,edgecolor="black", label="max_depth=5")
plt.scatter(y_3[:, 0], y_3[:, 1], c="orange", s=s,edgecolor="black", label="max_depth=8")
plt.xlim([-6, 6])
plt.ylim([-6, 6])
plt.xlabel("target 1")
plt.ylabel("target 2")
plt.title("Multi-output Decision Tree Regression")
plt.legend(loc="best")
plt.show()
更多推荐
多输出决策树回归
发布评论