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
|
|
|
|
|
learn 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
|
|
|
|
|
`max_depth` parameter) is set to high, the decision trees learn too fine
|
|
|
|
|
details of the training data and learn from the noise, i.e. they overfit.
|
2011-09-13 19:52:41 +08:00
|
|
|
"""
|
|
|
|
|
print __doc__
|
|
|
|
|
|
|
|
|
|
###############################################################################
|
|
|
|
|
# Generate sample data
|
|
|
|
|
import numpy as np
|
|
|
|
|
|
2011-09-26 01:59:22 +08:00
|
|
|
# Create a random number generator
|
|
|
|
|
rng = np.random.RandomState(1)
|
|
|
|
|
X = np.sort(5*rng.rand(80, 1), axis=0)
|
2011-09-13 19:52:41 +08:00
|
|
|
y = np.sin(X).ravel()
|
|
|
|
|
|
|
|
|
|
###############################################################################
|
|
|
|
|
# Add noise to targets
|
2011-09-26 01:59:22 +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)
|
|
|
|
|
y_1 = clf_1.fit(X, y).predict(X)
|
|
|
|
|
y_2 = clf_2.fit(X, y).predict(X)
|
|
|
|
|
|
|
|
|
|
###############################################################################
|
|
|
|
|
# look at the results
|
|
|
|
|
import pylab as pl
|
2011-09-26 01:59:22 +08:00
|
|
|
pl.figure(1, figsize=(5, 4))
|
|
|
|
|
pl.clf()
|
2011-09-13 19:52:41 +08:00
|
|
|
pl.scatter(X, y, c='k', label='data')
|
2011-09-26 01:59:22 +08:00
|
|
|
pl.plot(X, y_1, c='g', label='max_depth=2', linewidth=2)
|
|
|
|
|
pl.plot(X, y_2, c='r', label='max_depth=5', linewidth=2)
|
|
|
|
|
pl.axis('tight')
|
2011-09-13 19:52:41 +08:00
|
|
|
pl.xlabel('data')
|
|
|
|
|
pl.ylabel('target')
|
|
|
|
|
pl.title('Decision Tree Regression')
|
2011-09-26 01:59:22 +08:00
|
|
|
pl.legend(loc='best')
|
|
|
|
|
pl.show()
|