python Sklearn中的SVC分类器支持向量类

时间:2019-02-20 16:13:23

标签: python machine-learning scikit-learn svm

如何找出sklearn SVC中哪些支持向量属于哪个类?

model = clf.fit(X,y) 

vectors = model.support_vectors_

哪个向量属于哪个决策边界?

1 个答案:

答案 0 :(得分:1)

您可以使用SVC.support_属性。 support_属性为SVC.support_vectors_中的每个支持向量提供训练数据的索引。您可以按以下方式检索每个支持向量的类(给出您的示例):

X[model.support_]

更完整的示例:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_classification
from sklearn.svm import SVC

svc = SVC(kernel='linear', C=0.025)
X, y = make_classification(n_samples=500, n_features=2, n_redundant=0, n_informative=2, random_state=1, n_clusters_per_class=1)
rng = np.random.RandomState(2)
X += 2 * rng.uniform(size=X.shape)
X = StandardScaler().fit_transform(X)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=.4, random_state=42)
cm_bright = ListedColormap(['#FF0000', '#0000FF'])
fig, ax = plt.subplots(figsize=(18,12))
ax.scatter(X_tr[:, 0], X_tr[:, 1], c=y_tr, cmap=cm_bright)
svc.fit(X_tr, y_tr)
y_tr[svc.support_]
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1])
fig2, ax2 = plt.subplots(figsize=(18,12))
ax2.scatter(X_tr[:, 0], X_tr[:, 1], c=y_tr, cmap=cm_bright)
ax2.scatter(svc.support_vectors_[:, 0], svc.support_vectors_[:, 1])    
fig3, ax3 = plt.subplots(figsize=(18,12))
ax3.scatter(X_tr[:, 0], X_tr[:, 1], c=y_tr, cmap=cm_bright)
ax3.scatter(svc.support_vectors_[:, 0], svc.support_vectors_[:, 1], c=y_tr[svc.support_], cmap=cm_bright)

enter image description here enter image description here enter image description here