决策树没有很好的边界。它们具有多个边界,将特征空间分层划分为矩形区域。
在我的实施中节点收获我编写了解析 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
and y
- 这些是分别位于 x 轴和 y 轴上的特征。默认为x=0, y=1
它适用于任何具有多个特征的数据集。然而,在 Iris 数据集中,第一个维度不是很有趣,因此我们将使用不同的设置。
功能decision_areas
也不知道数据集的范围。通常,决策树具有向无穷延伸的开放决策范围(例如,每当萼片长度小于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)