2011-09-13 19:52:41 +08:00
|
|
|
"""
|
|
|
|
|
===================================================================
|
|
|
|
|
Decision Tree Regression
|
|
|
|
|
===================================================================
|
|
|
|
|
|
2011-09-26 01:59:22 +08:00
|
|
|
1D regression with :ref:`decision trees <tree>`: the decision tree is
|
|
|
|
|
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
|
|
|
|
2011-09-26 01:59:22 +08:00
|
|
|
We can see that if the maximum depth of the tree (controled 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
|
|
|
"""
|
|
|
|
|
print __doc__
|
|
|
|
|
|
|
|
|
|
import numpy as np
|
|
|
|
|
|
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
|
|
|
|
|
from sklearn.tree import DecisionTreeRegressor
|
|
|
|
|
|
|
|
|
|
clf_1 = DecisionTreeRegressor(max_depth=2)
|
|
|
|
|
clf_2 = DecisionTreeRegressor(max_depth=5)
|
2011-11-16 21:14:56 +08:00
|
|
|
clf_1.fit(X, y)
|
|
|
|
|
clf_2.fit(X, y)
|
|
|
|
|
|
|
|
|
|
# Predict
|
|
|
|
|
X_test = np.arange(0.0, 5.0, 0.01)[:, np.newaxis]
|
|
|
|
|
y_1 = clf_1.predict(X_test)
|
|
|
|
|
y_2 = clf_2.predict(X_test)
|
2011-09-13 19:52:41 +08:00
|
|
|
|
2011-12-19 22:53:00 +08:00
|
|
|
# Plot the results
|
2011-09-13 19:52:41 +08:00
|
|
|
import pylab as pl
|
2011-12-19 22:53:00 +08:00
|
|
|
|
|
|
|
|
pl.figure()
|
2011-11-17 02:21:07 +08:00
|
|
|
pl.scatter(X, y, c="k", label="data")
|
|
|
|
|
pl.plot(X_test, y_1, c="g", label="max_depth=2", linewidth=2)
|
|
|
|
|
pl.plot(X_test, y_2, c="r", label="max_depth=5", linewidth=2)
|
|
|
|
|
pl.xlabel("data")
|
|
|
|
|
pl.ylabel("target")
|
|
|
|
|
pl.title("Decision Tree Regression")
|
2011-12-19 22:53:00 +08:00
|
|
|
pl.legend()
|
2011-09-26 01:59:22 +08:00
|
|
|
pl.show()
|