scikit-learn/examples/tree/plot_iris_dtc.py

72 lines
2.2 KiB
Python
Raw Normal View History

"""
2011-11-16 22:54:06 +08:00
================================================================
Plot the decision surface of a decision tree on the iris dataset
================================================================
Plot the decision surface of a decision tree trained on pairs
of features of the iris dataset.
2011-09-26 01:30:23 +08:00
See :ref:`decision tree <tree>` for more information on the estimator.
2011-11-16 22:54:06 +08:00
For each pair of iris features, the decision tree learns decision
boundaries made of combinations of simple thresholding rules inferred from
the training samples.
[MRG] Matplotlib tree plotting (#9251) * add reingold tillford tree layout algorithm * add first silly implementation of matplotlib based plotting for trees * object oriented design for export_graphviz so it can be extended * add class for mlp export * add colors * separately scale x and y, add arrowheads, fix strings * implement max_depth * don't use alpha for coloring because it makes boxes transparent * remove unused variables * vertical center of boxes * fix/simplify newline trimming * somewhere in the middle of stuff trying to get rid of scalex, scaley * remove "find_longest_child" for now, fix tests * make scalex and scaley internal, and ax local. render everything once to get the bbox sizes, then again to actually plot it with known extents. * add some margin to the max bbox width * add _BaseTreeExporter baseclass * add docstring to plot_tree * use data coordinates so we can put the plot in a subplot, remove some hacks. * remove scalex, scaley, add automatic font size * use rendered stuff for setting limits (well nearly there) * import plot_tree into tree module * set limits before font size adjustment? * add tree plotting via matplotlib to iris example and to docs * pep8 fix * skip doctest on plot_tree because matplotlib is not installed on all CI machines * redo everything in axis pixel coordinates re-introduce scalex, scaley add max_extents to tree to get tree size before plotting * fix max-depth parent node positioning and don't consider deep nodes in layouting * consider height in fontsize computation in case someone gave us a very flat figure * fix error when max_depth is None * add docstring for tree plotting fontsize * starting on jnothman's review * renaming fixes * whatsnew for tree plotting * clear axes prior to doing anything. * fix doctests * skip matplotlib doctest * trying to debug circle failure * trying to show full traceback * more print debugging * remove debugging crud * hack around matplotlib <1.5 issues * copy bbox args because old matplotlib is weird. * pep8 fixes * add explicit boxstyle * more pep8 * even more pep8 * add comment about matplotlib version requirement * remove redundant file * add whatsnew entry that the merge lost * fix merge issue * more merge issues * whitespace ... * remove doctest skip to see what's happening * added some simple invariance tests buchheim function * refactor ___init__ into superclass * added some tests of plot_tree * put skip back in, fix typo, fix versionadded number * remove unused parameters special_characters and parallel_leaves from mpl plotting * rename tests to test_reingold_tilford * added license header from pymag-trees repo * remove duplicate test file.
2018-10-12 03:42:02 +08:00
We also show the tree structure of a model built on all of the features.
"""
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
2011-12-19 22:53:00 +08:00
2011-11-16 21:44:16 +08:00
from sklearn.datasets import load_iris
[MRG] Matplotlib tree plotting (#9251) * add reingold tillford tree layout algorithm * add first silly implementation of matplotlib based plotting for trees * object oriented design for export_graphviz so it can be extended * add class for mlp export * add colors * separately scale x and y, add arrowheads, fix strings * implement max_depth * don't use alpha for coloring because it makes boxes transparent * remove unused variables * vertical center of boxes * fix/simplify newline trimming * somewhere in the middle of stuff trying to get rid of scalex, scaley * remove "find_longest_child" for now, fix tests * make scalex and scaley internal, and ax local. render everything once to get the bbox sizes, then again to actually plot it with known extents. * add some margin to the max bbox width * add _BaseTreeExporter baseclass * add docstring to plot_tree * use data coordinates so we can put the plot in a subplot, remove some hacks. * remove scalex, scaley, add automatic font size * use rendered stuff for setting limits (well nearly there) * import plot_tree into tree module * set limits before font size adjustment? * add tree plotting via matplotlib to iris example and to docs * pep8 fix * skip doctest on plot_tree because matplotlib is not installed on all CI machines * redo everything in axis pixel coordinates re-introduce scalex, scaley add max_extents to tree to get tree size before plotting * fix max-depth parent node positioning and don't consider deep nodes in layouting * consider height in fontsize computation in case someone gave us a very flat figure * fix error when max_depth is None * add docstring for tree plotting fontsize * starting on jnothman's review * renaming fixes * whatsnew for tree plotting * clear axes prior to doing anything. * fix doctests * skip matplotlib doctest * trying to debug circle failure * trying to show full traceback * more print debugging * remove debugging crud * hack around matplotlib <1.5 issues * copy bbox args because old matplotlib is weird. * pep8 fixes * add explicit boxstyle * more pep8 * even more pep8 * add comment about matplotlib version requirement * remove redundant file * add whatsnew entry that the merge lost * fix merge issue * more merge issues * whitespace ... * remove doctest skip to see what's happening * added some simple invariance tests buchheim function * refactor ___init__ into superclass * added some tests of plot_tree * put skip back in, fix typo, fix versionadded number * remove unused parameters special_characters and parallel_leaves from mpl plotting * rename tests to test_reingold_tilford * added license header from pymag-trees repo * remove duplicate test file.
2018-10-12 03:42:02 +08:00
from sklearn.tree import DecisionTreeClassifier, plot_tree
2011-11-16 21:44:16 +08:00
# Parameters
n_classes = 3
plot_colors = "ryb"
2011-11-16 21:44:16 +08:00
plot_step = 0.02
2011-12-19 22:53:00 +08:00
2011-11-16 21:44:16 +08:00
# Load data
iris = load_iris()
2011-09-26 01:30:23 +08:00
for pairidx, pair in enumerate([[0, 1], [0, 2], [0, 3],
[1, 2], [1, 3], [2, 3]]):
# We only take the two corresponding features
2011-11-16 21:44:16 +08:00
X = iris.data[:, pair]
y = iris.target
2011-11-16 21:44:16 +08:00
# Train
clf = DecisionTreeClassifier().fit(X, y)
2011-11-16 21:44:16 +08:00
# Plot the decision boundary
plt.subplot(2, 3, pairidx + 1)
2011-11-16 21:44:16 +08:00
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
2011-11-16 21:44:16 +08:00
xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step),
np.arange(y_min, y_max, plot_step))
plt.tight_layout(h_pad=0.5, w_pad=0.5, pad=2.5)
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
cs = plt.contourf(xx, yy, Z, cmap=plt.cm.RdYlBu)
2011-11-16 22:54:06 +08:00
plt.xlabel(iris.feature_names[pair[0]])
plt.ylabel(iris.feature_names[pair[1]])
2011-11-16 21:44:16 +08:00
# Plot the training points
2013-02-14 09:05:35 +08:00
for i, color in zip(range(n_classes), plot_colors):
idx = np.where(y == i)
plt.scatter(X[idx, 0], X[idx, 1], c=color, label=iris.target_names[i],
cmap=plt.cm.RdYlBu, edgecolor='black', s=15)
plt.suptitle("Decision surface of a decision tree using paired features")
plt.legend(loc='lower right', borderpad=0, handletextpad=0)
plt.axis("tight")
[MRG] Matplotlib tree plotting (#9251) * add reingold tillford tree layout algorithm * add first silly implementation of matplotlib based plotting for trees * object oriented design for export_graphviz so it can be extended * add class for mlp export * add colors * separately scale x and y, add arrowheads, fix strings * implement max_depth * don't use alpha for coloring because it makes boxes transparent * remove unused variables * vertical center of boxes * fix/simplify newline trimming * somewhere in the middle of stuff trying to get rid of scalex, scaley * remove "find_longest_child" for now, fix tests * make scalex and scaley internal, and ax local. render everything once to get the bbox sizes, then again to actually plot it with known extents. * add some margin to the max bbox width * add _BaseTreeExporter baseclass * add docstring to plot_tree * use data coordinates so we can put the plot in a subplot, remove some hacks. * remove scalex, scaley, add automatic font size * use rendered stuff for setting limits (well nearly there) * import plot_tree into tree module * set limits before font size adjustment? * add tree plotting via matplotlib to iris example and to docs * pep8 fix * skip doctest on plot_tree because matplotlib is not installed on all CI machines * redo everything in axis pixel coordinates re-introduce scalex, scaley add max_extents to tree to get tree size before plotting * fix max-depth parent node positioning and don't consider deep nodes in layouting * consider height in fontsize computation in case someone gave us a very flat figure * fix error when max_depth is None * add docstring for tree plotting fontsize * starting on jnothman's review * renaming fixes * whatsnew for tree plotting * clear axes prior to doing anything. * fix doctests * skip matplotlib doctest * trying to debug circle failure * trying to show full traceback * more print debugging * remove debugging crud * hack around matplotlib <1.5 issues * copy bbox args because old matplotlib is weird. * pep8 fixes * add explicit boxstyle * more pep8 * even more pep8 * add comment about matplotlib version requirement * remove redundant file * add whatsnew entry that the merge lost * fix merge issue * more merge issues * whitespace ... * remove doctest skip to see what's happening * added some simple invariance tests buchheim function * refactor ___init__ into superclass * added some tests of plot_tree * put skip back in, fix typo, fix versionadded number * remove unused parameters special_characters and parallel_leaves from mpl plotting * rename tests to test_reingold_tilford * added license header from pymag-trees repo * remove duplicate test file.
2018-10-12 03:42:02 +08:00
plt.figure()
clf = DecisionTreeClassifier().fit(iris.data, iris.target)
plot_tree(clf, filled=True)
plt.show()