# -*-coding:utf-8-*-
import numpy as np
from sklearn import tree
import matplotlib.pyplot as plt
plt.switch_backend("TkAgg")
# 创建了一个随机数生成器对象 rng
rng=np.random.RandomState(1)
print("rng",rng)
#5*rng.rand(80,1)生成一个80行、1列的数组,数组中的每个元素都是从0到5之间的随机数。然后,np.sort函数对这个数组进行排序,axis=0表示按行(也就是每一列)排序。
#axis=0,数组只有行,没有列
X=np.sort(5*rng.rand(80,1),axis=0)
#ravel()把二维数组变为一位数组
y=np.sin(X).ravel()
#选取0,5,10,15,20....,让这些下标数字加上噪声
y[::5]+=3*(0.5-rng.rand(16))
regr_1=tree.DecisionTreeRegressor(max_depth=2)
regr_2=tree.DecisionTreeRegressor(max_depth=5)
clf1=regr_1.fit(X,y)
clf2=regr_2.fit(X,y)
#转为二维数组
X_test=np.reshape( np.arange(0.0,5.0,0.01),(-1,1) )
# X_test=np.arrange(0.0,5.0,0.01)[:,np.newaxis]
y_1=regr_1.predict(X_test)
y_2=regr_2.predict(X_test)
plt.figure()
plt.scatter(X,y,s=20,edgecolors="black",c="darkorange",label="data")
plt.plot(X_test,y_1,color="cornflowerblue",label="max_depth=2",linewidth=2)
plt.plot(X_test,y_2,color="yellowgreen",label="max_depth=5",linewidth=2)
plt.xlabel("data")
plt.ylabel("target")
plt.title("Decision Tree Regreesion")
plt.legend()
plt.show()