- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试在外部可视化平台上创建曲面图。我正在使用 sklearn decision tree documentation page 上的 iris 数据集.我也使用相同的方法来创建我的决策曲面图。虽然我的最终目标不是 matplot lib visual,所以我从这里将数据输入到我的可视化软件。为此,我只是在 xx
、yy
和 Z 上调用了
并写了一个包含这些列表的 JSON 文件。 flatten()
和 tolist()
问题是当我尝试绘制它时,我的可视化程序崩溃了。事实证明数据太大了。展平后,列表的长度 >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)
只要不同颜色的区域相遇,就会有一个决策边界。我想可以通过适度的努力来提取这些边界线,但我会把它留给任何感兴趣的人。
rectangles
是一个 numpy 数组。每行对应一个矩形,列为 [left, right, top, bottom, class]
。
鸢尾花数据集包含三个类别,而不是示例中的两个类别。所以我们必须向 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)
请注意左上角的红色和绿色区域有奇怪的重叠。发生这种情况是因为树在四个维度上做出决策,但我们只能显示两个。没有真正解决这个问题的干净方法。高维分类器在低维空间中通常没有很好的决策边界。
因此,如果您对您得到的分类器更感兴趣。您可以根据各种维度组合生成不同的 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)
最后,这里是实现:
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/
我需要将文本放在 中在一个 Div 中,在另一个 Div 中,在另一个 Div 中。所以这是它的样子: #document Change PIN
奇怪的事情发生了。 我有一个基本的 html 代码。 html,头部, body 。(因为我收到了一些反对票,这里是完整的代码) 这是我的CSS: html { backgroun
我正在尝试将 Assets 中的一组图像加载到 UICollectionview 中存在的 ImageView 中,但每当我运行应用程序时它都会显示错误。而且也没有显示图像。 我在ViewDidLoa
我需要根据带参数的 perl 脚本的输出更改一些环境变量。在 tcsh 中,我可以使用别名命令来评估 perl 脚本的输出。 tcsh: alias setsdk 'eval `/localhome/
我使用 Windows 身份验证创建了一个新的 Blazor(服务器端)应用程序,并使用 IIS Express 运行它。它将显示一条消息“Hello Domain\User!”来自右上方的以下 Ra
这是我的方法 void login(Event event);我想知道 Kotlin 中应该如何 最佳答案 在 Kotlin 中通配符运算符是 * 。它指示编译器它是未知的,但一旦知道,就不会有其他类
看下面的代码 for story in book if story.title.length < 140 - var story
我正在尝试用 C 语言学习字符串处理。我写了一个程序,它存储了一些音乐轨道,并帮助用户检查他/她想到的歌曲是否存在于存储的轨道中。这是通过要求用户输入一串字符来完成的。然后程序使用 strstr()
我正在学习 sscanf 并遇到如下格式字符串: sscanf("%[^:]:%[^*=]%*[*=]%n",a,b,&c); 我理解 %[^:] 部分意味着扫描直到遇到 ':' 并将其分配给 a。:
def char_check(x,y): if (str(x) in y or x.find(y) > -1) or (str(y) in x or y.find(x) > -1):
我有一种情况,我想将文本文件中的现有行包含到一个新 block 中。 line 1 line 2 line in block line 3 line 4 应该变成 line 1 line 2 line
我有一个新项目,我正在尝试设置 Django 调试工具栏。首先,我尝试了快速设置,它只涉及将 'debug_toolbar' 添加到我的已安装应用程序列表中。有了这个,当我转到我的根 URL 时,调试
在 Matlab 中,如果我有一个函数 f,例如签名是 f(a,b,c),我可以创建一个只有一个变量 b 的函数,它将使用固定的 a=a1 和 c=c1 调用 f: g = @(b) f(a1, b,
我不明白为什么 ForEach 中的元素之间有多余的垂直间距在 VStack 里面在 ScrollView 里面使用 GeometryReader 时渲染自定义水平分隔线。 Scrol
我想知道,是否有关于何时使用 session 和 cookie 的指南或最佳实践? 什么应该和什么不应该存储在其中?谢谢! 最佳答案 这些文档很好地了解了 session cookie 的安全问题以及
我在 scipy/numpy 中有一个 Nx3 矩阵,我想用它制作一个 3 维条形图,其中 X 轴和 Y 轴由矩阵的第一列和第二列的值、高度确定每个条形的 是矩阵中的第三列,条形的数量由 N 确定。
假设我用两种不同的方式初始化信号量 sem_init(&randomsem,0,1) sem_init(&randomsem,0,0) 现在, sem_wait(&randomsem) 在这两种情况下
我怀疑该值如何存储在“WORD”中,因为 PStr 包含实际输出。? 既然Pstr中存储的是小写到大写的字母,那么在printf中如何将其给出为“WORD”。有人可以吗?解释一下? #include
我有一个 3x3 数组: var my_array = [[0,1,2], [3,4,5], [6,7,8]]; 并想获得它的第一个 2
我意识到您可以使用如下方式轻松检查焦点: var hasFocus = true; $(window).blur(function(){ hasFocus = false; }); $(win
我是一名优秀的程序员,十分优秀!