Select 5个最接近SVM超车道的数据点

Select 5 data points closest to SVM hyperlane

我已经使用 Sklearn 编写了 Python 代码来对我的数据集进行聚类:

af = AffinityPropagation().fit(X)
cluster_centers_indices = af.cluster_centers_indices_
labels = af.labels_
n_clusters_= len(cluster_centers_indices)

我正在探索聚类查询的使用,因此通过以下方式形成初始训练数据集:

td_title =[]
td_abstract = []
td_y= []
for each in centers:
    td_title.append(title[each])
    td_abstract.append(abstract[each])
    td_y.append(y[each])

然后我通过以下方式训练我的模型(SVM):

clf = svm.SVC()
clf.fit(X, data_y)

我希望编写一个函数,给定中心、模型、X 值和 Y 值将附加模型最不确定的 5 个数据点,即。最接近超平面的数据点。我该怎么做?

我对你的流程的第一步并不完全清楚,但这里有一个 "Select(ing) 5 data points closest to SVM hyperplane" 的建议。 scikit 文档定义 decision_function as the distance of the samples to the separating hyperplane. The method returns an array which can be sorted with argsort 以查找 "top/bottom N samples".

this basic scikit example之后,定义一个函数closestN到return最接近超平面的样本。

import numpy as np

def closestN(X_array, n):
    # array of sample distances to the hyperplane
    dists = clf.decision_function(X_array)
    # absolute distance to hyperplane
    absdists = np.abs(dists)

    return absdists.argsort()[:n]

将这两行添加到scikit示例中以查看实现的功能:

closest_samples = closestN(X, 5)
plt.scatter(X[closest_samples][:, 0], X[closest_samples][:, 1], color='yellow')

原创

突出显示最接近的样本

如果您需要将示例附加到某个列表,您可以 somelist.append(closestN(X, 5))。如果您需要示例值,您可以执行类似 somelist.append(X[closestN(X, 5)]).

的操作
closestN(X, 5)
array([ 1, 20, 14, 31, 24])

X[closestN(X, 5)]
array([[-1.02126202,  0.2408932 ],
       [ 0.95144703,  0.57998206],
       [-0.46722079, -0.53064123],
       [ 1.18685372,  0.2737174 ],
       [ 0.38610215,  1.78725972]])