决策树没有很好的边界。它们有多个边界,将特征空间分层划分为矩形区域。
在我的Node Harvest 实现中,我编写了解析 scikit 决策树并提取决策区域的函数。对于这个答案,我修改了部分代码以返回对应于树决策区域的矩形列表。使用任何绘图库都应该很容易绘制这些矩形。下面是一个使用 matplotlib 的例子:
n = 100
np.random.seed(42)
x = np.concatenate([np.random.randn(n, 2) + 1, np.random.randn(n, 2) - 1])
y = ['b'] * n + ['r'] * n
plt.scatter(x[:, 0], x[:, 1], c=y)
dtc = DecisionTreeClassifier().fit(x, y)
rectangles = decision_areas(dtc, [-3, 3, -3, 3])
plot_areas(rectangles)
plt.xlim(-3, 3)
plt.ylim(-3, 3)
只要不同颜色的区域相遇,就会有一个决策边界。我想可以通过适度的努力仅提取这些边界线,但我会将其留给任何感兴趣的人。
rectangles 是一个 numpy 数组。每行对应一个矩形,列为[left, right, top, bottom, class]。
更新:应用到 Iris 数据集
Iris 数据集包含三个类,而不是示例中的 2 个。所以我们必须为plot_areas 函数添加另一种颜色:color = ['b', 'r', 'g'][int(rect[4])]。
此外,数据集是 4 维的(它包含四个特征),但我们只能在 2D 中绘制两个特征。我们需要选择要绘制的特征并告诉decision_area 函数。该函数有两个参数x 和y——它们分别是x 和y 轴上的特征。默认值为x=0, y=1,它适用于具有多个特征的任何数据集。但是,在 Iris 数据集中,第一个维度并不是很有趣,因此我们将使用不同的设置。
函数decision_areas 也不知道数据集的范围。决策树通常具有向无穷大扩展的开放决策范围(例如,只要 sepal length 小于 xyz,它就是 B 类)。在这种情况下,我们需要人为地缩小绘图范围。我为示例数据集选择了-3..3,但对于 iris 数据集,其他范围是合适的(从来没有负值,一些特征超出 3)。
在这里,我们在 0..7 和 0..5 的范围内绘制最后两个特征的决策区域:
from sklearn.datasets import load_iris
data = load_iris()
x = data.data
y = data.target
dtc = DecisionTreeClassifier().fit(x, y)
rectangles = decision_areas(dtc, [0, 7, 0, 5], x=2, y=3)
plt.scatter(x[:, 2], x[:, 3], c=y)
plot_areas(rectangles)
请注意左上角的红色和绿色区域如何奇怪地重叠。发生这种情况是因为树在四个维度上做出决策,但我们只能显示两个。没有真正干净的方法解决这个问题。高维分类器在低维空间中通常没有很好的决策边界。
因此,如果您对分类器更感兴趣,那就是您所得到的。您可以沿各种维度组合生成不同的视图,但表示的有用性是有限的。
但是,如果您对数据比对分类器更感兴趣,则可以在拟合之前限制维度。在这种情况下,分类器仅在二维空间中做出决策,我们可以绘制出不错的决策区域:
from sklearn.datasets import load_iris
data = load_iris()
x = data.data[:, [2, 3]]
y = data.target
dtc = DecisionTreeClassifier().fit(x, y)
rectangles = decision_areas(dtc, [0, 7, 0, 3], x=0, y=1)
plt.scatter(x[:, 0], x[:, 1], c=y)
plot_areas(rectangles)
最后,实现如下:
import numpy as np
from collections import deque
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import _tree as ctree
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
class AABB:
"""Axis-aligned bounding box"""
def __init__(self, n_features):
self.limits = np.array([[-np.inf, np.inf]] * n_features)
def split(self, f, v):
left = AABB(self.limits.shape[0])
right = AABB(self.limits.shape[0])
left.limits = self.limits.copy()
right.limits = self.limits.copy()
left.limits[f, 1] = v
right.limits[f, 0] = v
return left, right
def tree_bounds(tree, n_features=None):
"""Compute final decision rule for each node in tree"""
if n_features is None:
n_features = np.max(tree.feature) + 1
aabbs = [AABB(n_features) for _ in range(tree.node_count)]
queue = deque([0])
while queue:
i = queue.pop()
l = tree.children_left[i]
r = tree.children_right[i]
if l != ctree.TREE_LEAF:
aabbs[l], aabbs[r] = aabbs[i].split(tree.feature[i], tree.threshold[i])
queue.extend([l, r])
return aabbs
def decision_areas(tree_classifier, maxrange, x=0, y=1, n_features=None):
""" Extract decision areas.
tree_classifier: Instance of a sklearn.tree.DecisionTreeClassifier
maxrange: values to insert for [left, right, top, bottom] if the interval is open (+/-inf)
x: index of the feature that goes on the x axis
y: index of the feature that goes on the y axis
n_features: override autodetection of number of features
"""
tree = tree_classifier.tree_
aabbs = tree_bounds(tree, n_features)
rectangles = []
for i in range(len(aabbs)):
if tree.children_left[i] != ctree.TREE_LEAF:
continue
l = aabbs[i].limits
r = [l[x, 0], l[x, 1], l[y, 0], l[y, 1], np.argmax(tree.value[i])]
rectangles.append(r)
rectangles = np.array(rectangles)
rectangles[:, [0, 2]] = np.maximum(rectangles[:, [0, 2]], maxrange[0::2])
rectangles[:, [1, 3]] = np.minimum(rectangles[:, [1, 3]], maxrange[1::2])
return rectangles
def plot_areas(rectangles):
for rect in rectangles:
color = ['b', 'r'][int(rect[4])]
print(rect[0], rect[1], rect[2] - rect[0], rect[3] - rect[1])
rp = Rectangle([rect[0], rect[2]],
rect[1] - rect[0],
rect[3] - rect[2], color=color, alpha=0.3)
plt.gca().add_artist(rp)