Ara*_*ida 6 python matplotlib python-3.x scikit-learn
我正在尝试在外部可视化平台上创建曲面图。我正在使用sklearn 决策树文档页面上的 iris 数据集。我也使用相同的方法来创建我的决策曲面图。我的最终目标不是 matplot lib 视觉对象,所以从这里我将数据输入到我的可视化软件中。要做到这一点,我刚打电话flatten()和tolist()上xx,yy并Z写下了包含这些列出了JSON文件。
问题是当我尝试绘制它时,我的可视化程序崩溃了。结果发现数据太大了。展平后,列表的长度大于 86,000。这是因为步长/绘图步长非常小.02。因此,根据模型的预测,它本质上是在数据的最小值和最大值的范围内逐步进行并绘制/填充。它有点像像素网格;我将大小缩小到只有 2000 的数组,并注意到坐标只是来回移动的线(最终包含整个坐标平面)。
问题:我可以检索决策边界线本身的 x,y 坐标吗(而不是遍历整个平面)?理想情况下,列表只包含每条线的转折点。或者,是否有其他完全不同的方式来重新创建这个图,以便它在计算上更有效率?
这可以通过将contourf()调用替换为countour():
我只是不知道如何获取有关这些线上的数据(通过xx,yy并Z或其他可能的方式?)。
注意:只要计算效率高,我对包含行格式的列表/或数据结构的确切格式并不挑剔。例如,对于上面的第一个图,一些红色区域实际上是预测空间中的孤岛,所以这可能意味着我们必须像处理它自己的线一样处理它。我猜只要该类与 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)
Run Code Online (Sandbox Code Playgroud)
不同颜色的区域相遇的地方就有一个决策边界。我想可以通过适度的努力来提取这些边界线,但我会将其留给感兴趣的任何人。
rectangles是一个numpy数组。每一行对应一个矩形,列是[left, right, top, bottom, class]。
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也不知道数据集的范围。通常,决策树具有扩展到无穷大的开放决策范围(例如,每当萼片长度小于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)
Run Code Online (Sandbox Code Playgroud)
请注意左上角的红色和绿色区域如何奇怪地重叠。发生这种情况是因为树在四个维度上做出决策,但我们只能显示两个维度。没有真正干净的方法来解决这个问题。高维分类器在低维空间中通常没有很好的决策边界。
所以如果你对分类器更感兴趣,那就是你得到的。您可以沿各种尺寸组合生成不同的视图,但表示的有用性是有限的。
但是,如果您对数据比对分类器更感兴趣,则可以在拟合之前限制维度。在这种情况下,分类器只在二维空间中做出决策,我们可以绘制出很好的决策区域:
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)
Run Code Online (Sandbox Code Playgroud)
最后,这是实现:
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2855 次 |
| 最近记录: |