gpt4 book ai didi

python - 从 SKlearn 决策树中检索决策边界线(x,y 坐标格式)

转载 作者:太空狗 更新时间:2023-10-30 02:26:46 25 4
gpt4 key购买 nike

我正在尝试在外部可视化平台上创建曲面图。我正在使用 sklearn decision tree documentation page 上的 iris 数据集.我也使用相同的方法来创建我的决策曲面图。虽然我的最终目标不是 matplot lib visual,所以我从这里将数据输入到我的可视化软件。为此,我只是在 xxyyZ 上调用了 flatten()tolist() 并写了一个包含这些列表的 JSON 文件。

问题是当我尝试绘制它时,我的可视化程序崩溃了。事实证明数据太大了。展平后,列表的长度 >86,000。这是因为步长/绘图步长非常小 .02。因此,根据模型的预测,它本质上是在数据的最小值和最大值的范围内迈出一小步,并在进行时绘制/填充。它有点像像素网格;我将大小缩小到只有 2000 个数组,并注意到坐标只是来回移动的线(最终包含整个坐标平面)。

问题:我能否检索决策边界线本身的 x,y 坐标(而不是遍历整个平面)?理想情况下,列表只包含每条线的转折点。或者,是否有其他一些完全不同的方法可以重新创建此图,从而提高计算效率?

这可以通过将 contourf() 调用替换为 countour() 来稍微形象化:

enter image description here

我只是不确定如何检索管理这些线路的数据(通过 xxyyZ 或可能的其他方式? ).

注意:我对包含行格式的列表/数据结构的确切格式不挑剔,只要计算效率高即可。例如,对于上面的第一个图,一些红色区域实际上是预测空间中的孤岛,所以这可能意味着我们必须像处理它自己的线一样处理它。我猜只要该类与 x、y 坐标耦合,使用多少数组(包含坐标)来捕获决策边界应该无关紧要。

最佳答案

决策树没有很好的边界。它们有多个边界,将特征空间分层划分为矩形区域。

在我的 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)

enter image description here

只要不同颜色的区域相遇,就会有一个决策边界。我想可以通过适度的努力来提取这些边界线,但我会把它留给任何感兴趣的人。

rectangles 是一个 numpy 数组。每行对应一个矩形,列为 [left, right, top, bottom, class]


更新:Iris 数据集的应用

鸢尾花数据集包含三个类别,而不是示例中的两个类别。所以我们必须向 plot_areas 函数添加另一种颜色:color = ['b', 'r', 'g'][int(rect[4])] .此外,数据集是 4 维的(它包含四个特征),但我们只能在 2D 中绘制两个特征。我们需要选择绘制哪些特征并告诉 decision_area 函数。该函数有两个参数 xy - 这些分别是 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)

enter image description here

请注意左上角的红色和绿色区域有奇怪的重叠。发生这种情况是因为树在四个维度上做出决策,但我们只能显示两个。没有真正解决这个问题的干净方法。高维分类器在低维空间中通常没有很好的决策边界。

因此,如果您对您得到的分类器更感兴趣。您可以根据各种维度组合生成不同的 View ,但表示的有用性是有限的。

但是,如果您对数据比对分类器更感兴趣,则可以在拟合前限制维度。在这种情况下,分类器仅在二维空间中做出决策,我们可以绘制漂亮的决策区域:

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)

enter image description here


最后,这里是实现:

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)

关于python - 从 SKlearn 决策树中检索决策边界线(x,y 坐标格式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43929400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com