参考
官方文档,决策树的介绍
官方文档,回归树使用参数介绍
官方文档,回归树小的例子
scikit-learn决策树算法类库使用小结(分类回归树参数对比介绍与可视化方法)
官方回归树的example代码如下
print(__doc__)
# Import the necessary modules and libraries
import numpy as np
from sklearn.tree import DecisionTreeRegressor
import matplotlib.pyplot as plt
# Create a random dataset
rng = np.random.RandomState(1)
X = np.sort(5 * rng.rand(80, 1), axis=0)
y = np.sin(X).ravel()
y[::5] += 3 * (0.5 - rng.rand(16))
# Fit regression model
regr_1 = DecisionTreeRegressor(max_depth=2)
regr_2 = DecisionTreeRegressor(max_depth=5)
regr_1.fit(X, y)
regr_2.fit(X, y)
# Predict
X_test = np.arange(0.0, 5.0, 0.01)[:, np.newaxis]
y_1 = regr_1.predict(X_test)
y_2 = regr_2.predict(X_test)
# Plot the results
plt.figure()
plt.scatter(X, y, s=20, edgecolor="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 Regression")
plt.legend()
plt.show()
结果如图,max_depth = 2时拟合的没有max_depth = 5好
安装graphviz
可参考scikit-learn决策树算法类库使用小结
具体步骤如下
apt-get install graphviz
pip install graphviz
pip install pydotplus
用以下代码就可以可视化决策树了
from IPython.display import Image
from sklearn import tree
import pydotplus
#regr_1 和regr_2
dot_data = tree.export_graphviz(regr_1, out_file=None, #regr_1 是对应分类器
feature_names=['x'], #对应特征的名字
class_names=['y'], #对应类别的名字
filled=True, rounded=True,
special_characters=True)
graph = pydotplus.graph_from_dot_data(dot_data)
graph.write_png('example.png') #保存图像
Image(graph.create_png())
max_depth=2
max_depth=5
自己用y = x^2玩玩
X = []
y = []
for i in range (1,81):
X.append([i])
y.append(i**2)
X_test = []
for i in np.arange(1.0,81.0,0.2):
X_test.append([i])
regr_1 = DecisionTreeRegressor(max_depth=2)
regr_2 = DecisionTreeRegressor(max_depth=10)
regr_1.fit(X, y)
regr_2.fit(X, y)
y_1 = regr_1.predict(X_test)
y_2 = regr_2.predict(X_test)
plt.figure()
plt.scatter(X, y, s=20, edgecolor="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=10", linewidth=2)
plt.xlabel("data")
plt.ylabel("target")
plt.title("Decision Tree Regression")
plt.legend()
plt.show()
max_depth=2
max_depth=10