2011-09-13 19:52:41 +08:00
|
|
|
"""
|
|
|
|
|
===================================================================
|
|
|
|
|
Decision Tree Regression
|
|
|
|
|
===================================================================
|
|
|
|
|
|
2013-07-22 21:48:44 +08:00
|
|
|
A 1D regression with decision tree.
|
|
|
|
|
|
|
|
|
|
The :ref:`decision trees <tree>` is
|
2011-09-26 01:59:22 +08:00
|
|
|
used to fit a sine curve with addition noisy observation. As a result, it
|
2011-12-19 22:53:00 +08:00
|
|
|
learns local linear regressions approximating the sine curve.
|
2011-09-13 19:52:41 +08:00
|
|
|
|
2013-04-12 02:51:28 +08:00
|
|
|
We can see that if the maximum depth of the tree (controlled by the
|
2011-11-16 21:17:59 +08:00
|
|
|
`max_depth` parameter) is set too high, the decision trees learn too fine
|
2011-09-26 01:59:22 +08:00
|
|
|
details of the training data and learn from the noise, i.e. they overfit.
|
2011-09-13 19:52:41 +08:00
|
|
|
"""
|
|
|
|
|
|
2014-08-01 18:28:03 +08:00
|
|
|
# Import the necessary modules and libraries
|
2011-09-13 19:52:41 +08:00
|
|
|
import numpy as np
|
2014-08-01 18:28:03 +08:00
|
|
|
from sklearn.tree import DecisionTreeRegressor
|
|
|
|
|
import matplotlib.pyplot as plt
|
2011-09-13 19:52:41 +08:00
|
|
|
|
2011-12-19 22:53:00 +08:00
|
|
|
# Create a random dataset
|
2011-09-26 01:59:22 +08:00
|
|
|
rng = np.random.RandomState(1)
|
2011-11-17 02:21:07 +08:00
|
|
|
X = np.sort(5 * rng.rand(80, 1), axis=0)
|
2011-09-13 19:52:41 +08:00
|
|
|
y = np.sin(X).ravel()
|
2011-11-17 02:21:07 +08:00
|
|
|
y[::5] += 3 * (0.5 - rng.rand(16))
|
2011-09-13 19:52:41 +08:00
|
|
|
|
|
|
|
|
# Fit regression model
|
2015-06-18 03:20:23 +08:00
|
|
|
regr_1 = DecisionTreeRegressor(max_depth=2)
|
|
|
|
|
regr_2 = DecisionTreeRegressor(max_depth=5)
|
|
|
|
|
regr_1.fit(X, y)
|
|
|
|
|
regr_2.fit(X, y)
|
2011-11-16 21:14:56 +08:00
|
|
|
|
|
|
|
|
# Predict
|
|
|
|
|
X_test = np.arange(0.0, 5.0, 0.01)[:, np.newaxis]
|
2015-06-18 03:20:23 +08:00
|
|
|
y_1 = regr_1.predict(X_test)
|
|
|
|
|
y_2 = regr_2.predict(X_test)
|
2011-09-13 19:52:41 +08:00
|
|
|
|
2011-12-19 22:53:00 +08:00
|
|
|
# Plot the results
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.figure()
|
2017-06-07 19:23:12 +08:00
|
|
|
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)
|
2015-10-22 22:04:06 +08:00
|
|
|
plt.plot(X_test, y_2, color="yellowgreen", label="max_depth=5", linewidth=2)
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.xlabel("data")
|
|
|
|
|
plt.ylabel("target")
|
|
|
|
|
plt.title("Decision Tree Regression")
|
|
|
|
|
plt.legend()
|
|
|
|
|
plt.show()
|