scikit-learn/examples/tree/plot_tree_regression.py

50 lines
1.5 KiB
Python
Raw Normal View History

2011-09-13 19:52:41 +08:00
"""
===================================================================
Decision Tree Regression
===================================================================
A 1D regression with decision tree.
The :ref:`decision trees <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
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
details of the training data and learn from the noise, i.e. they overfit.
2011-09-13 19:52:41 +08:00
"""
print(__doc__)
2011-09-13 19:52:41 +08:00
# Import the necessary modules and libraries
2011-09-13 19:52:41 +08:00
import numpy as np
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
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
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)
2011-09-13 19:52:41 +08:00
2011-12-19 22:53:00 +08:00
# Plot the results
plt.figure()
2015-10-22 22:04:06 +08:00
plt.scatter(X, y, 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()