我想找到样本到经过训练的决策树分类器的决策边界的距离scikit学习。特征都是数字的,特征空间可以是任何大小。
到目前为止,我有一个基于示例 2D 案例的可视化here:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import make_moons
# Generate some example data
X, y = make_moons(noise=0.3, random_state=0)
# Train the classifier
clf = DecisionTreeClassifier(max_depth=2)
clf.fit(X, y)
# Plot
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, alpha=0.4)
plt.scatter(X[:, 0], X[:, 1], c=y, s=20, edgecolor='k')
plt.xlabel('a'); plt.ylabel('b');
据我所知,对于像 SVM 这样的其他分类器,这个距离可以通过数学计算 [1, 2, 3]。训练决策树后学到的规则定义了边界,也可能有助于通过算法计算距离[4, 5, 6]:
# Plot the trained tree
from sklearn import tree
import graphviz
dot_data = tree.export_graphviz(clf, feature_names=['a', 'b'], class_names=['1', '2'], filled=True)
graph = graphviz.Source(dot_data)