由于一个样本周围可能有多个决策边界,因此我将假设距离是指到最近决策边界的距离。
解决方案是递归树遍历算法。请注意,决策树不允许样本位于边界上,例如SVM,要素空间中的每个样本都必须属于其中一个类。因此,在这里,我们将继续一步一步地修改样本的特征,并且只要该区域导致一个带有不同标签的区域(而不是经过训练的分类器最初分配给该样本的区域),我们就认为我们已经达到了决策边界。
详细地说,像任何递归算法一样,我们要考虑两种主要情况:
- 基本情况,即我们在叶节点。我们只需检查当前样本是否具有不同的标签:如果是,则返回它,否则返回
None
。 - 非叶节点。有两个分支,我们将样本发送到两个分支。我们不会修改示例以将其发送到自然需要的分支。但是在将其发送到另一个分支之前,我们先查看节点的(特征,阈值)对,并修改样本的给定特征,使其恰好将其推向阈值的另一侧。
完整的python代码:
def f(node,x,orig_label): global dt,tree if tree.children_left[node]==tree.children_right[node]: #Meaning node is a leaf return [x] if dt.predict([x])[0]!=orig_label else [None] if x[tree.feature[node]]<=tree.threshold[node]: orig = f(tree.children_left[node],x,orig_label) xc = x.copy() xc[tree.feature[node]] = tree.threshold[node] + .01 modif = f(tree.children_right[node],xc,orig_label) else: orig = f(tree.children_right[node],x,orig_label) xc = x.copy() xc[tree.feature[node]] = tree.threshold[node] modif = f(tree.children_left[node],xc,orig_label) return [s for s in orig+modif if s is not None]
这将返回给我们一系列导致标签不同的叶子的样品列表。我们现在要做的就是取最近的一个:
dt = DecisionTreeClassifier(max_depth=2).fit(X,y)tree = dt.tree_res = f(0,x,dt.predict([x])[0]) # 0 is index of root nodeans = np.min([np.linalg.norm(x-n) for n in res])
例如:
蓝色是原始样本,黄色是“在”决策边界上最近的样本。



