【sklearn】SVM用于分类(SVC)

API说明:

中文:http://sklearn.apachecn.org/cn/0.19.0/modules/svm.html

英文:https://scikit-learn.org/stable/modules/svm.html

API使用:(SVC)(Support Vector Classification.)

from sklearn import svm
X = [[0, 0], [1, 1]]
y = [0, 1]
clf = svm.SVC()
clf.fit(X, y) 

#预测
clf.predict([[2., 2.]])
# 获得支持向量
clf.support_vectors_


# 获得支持向量的索引get indices of support vectors
clf.support_ 

# 为每一个类别获得支持向量的数量
clf.n_support_ 

用于多分类:

X = [[0], [1], [2], [3]]
Y = [0, 1, 2, 3]
clf = svm.SVC(decision_function_shape='ovo')#一对一
clf.fit(X, Y) 

dec = clf.decision_function([[1]])
dec.shape[1] # 4 classes: 4*3/2 = 6

clf.decision_function_shape = "ovr"#一对多
dec = clf.decision_function([[1]])
dec.shape[1] # 4 classes

参数说明:

https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html

class sklearn.svm.SVC(C=1.0kernel=’rbf’degree=3gamma=’auto_deprecated’coef0=0.0shrinking=Trueprobability=Falsetol=0.001

 cache_size=200class_weight=Noneverbose=Falsemax_iter=-1decision_function_shape=’ovr’random_state=None)

参数:

  • C:惩罚项,默认1.0
  • kernel:核函数,默认‘rbf’。可自定义,根据其预先计算内核矩阵【n_samples, n_samples】
  • degree:多项式核函数的次数('poly')。被所有其他内核忽略。
  • gamma :'rbf','poly'和'sigmoid'的核系数。当前默认值为'auto',它使用1 / n_features,如果gamma='scale'传递,则使用1 /(n_features * X.std())作为gamma的值。当前默认的gamma''auto'将在版本0.22中更改为'scale'。
  • coef0 :默认0.0.核函数中的独立项。它只在'poly'和'sigmoid'中很重要。
  • shrinking:默认True。是否使用收缩启发式。
  • probability:默认False。是否启用概率估计。必须在调用fit之前启用它,并且会减慢该方法的速度。
  • tol :默认0.001.容忍停止标准。
  • cache_size:指定内核缓存的大小(MB)
  • class_weight :{dict,'balanced'}。将类i的参数C设置为SVC的class_weight [i] * C. 如果没有给出,所有类都应该有一个权重。“平衡”模式使用y的值自动调整与输入数据中的类频率成反比的权重n_samples / (n_classes * np.bincount(y))
  • verbose:默认False。启用详细输出。请注意,此设置利用libsvm中的每进程运行时设置,如果启用,则可能无法在多线程上下文中正常运行。
  • max_iter :迭代的硬限制。默认-1(无限制)
  • decision_function_shape :默认’ovr‘。
  • random_state :默认 无。伪随机数生成器的种子在对数据进行混洗以用于概率估计时使用。如果是int,则random_state是随机数生成器使用的种子; 如果是RandomState实例,则random_state是随机数生成器; 如果没有,随机数生成器所使用的RandomState实例np.random。

属性:

  • support_ :支持向量索引。
  • support_vectors_ :支持向量。
  • n_support_ :每一类的支持向量数目
  • dual_coef_ :决策函数中支持向量的系数
  • coef_ :赋予特征的权重(原始问题中的系数)。这仅适用于线性内核。
  • intercept_ :决策函数中的常量。

实例:

https://scikit-learn.org/stable/auto_examples/svm/plot_iris.html#sphx-glr-auto-examples-svm-plot-iris-py

def make_meshgrid(x, y, h=.02):
    """Create a mesh of points to plot in

    Parameters
    ----------
    x: data to base x-axis meshgrid on
    y: data to base y-axis meshgrid on
    h: stepsize for meshgrid, optional

    Returns
    -------
    xx, yy : ndarray
    """
    x_min, x_max = x.min() - 1, x.max() + 1
    y_min, y_max = y.min() - 1, y.max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))
    return xx, yy

np.meshgrid:meshgrid函数将两个输入的数组x和y进行扩展,前一个的扩展与后一个有关,后一个的扩展与前一个有关,前一个是竖向扩展,后一个是横向扩展。

def plot_contours(ax, clf, xx, yy, **params):
    """Plot the decision boundaries for a classifier.

    Parameters
    ----------
    ax: matplotlib axes object
    clf: a classifier
    xx: meshgrid ndarray
    yy: meshgrid ndarray
    params: dictionary of params to pass to contourf, optional
    """
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    out = ax.contourf(xx, yy, Z, **params)
    return out

np.r_是按列连接两个矩阵,就是把两矩阵上下相加,要求列数相等,类似于pandas中的concat()。

np.c_是按行连接两个矩阵,就是把两矩阵左右相加,要求行数相等,类似于pandas中的merge()。

ax.contourf(xx, yy, Z, **params):contourf:将不会再绘制等高线(显然不同的颜色分界就表示等高线本身),

import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets

# import some data to play with
iris = datasets.load_iris()
# Take the first two features. We could avoid this by using a two-dim dataset
X = iris.data[:, :2]
y = iris.target

# we create an instance of SVM and fit out data. We do not scale our
# data since we want to plot the support vectors
C = 1.0  # SVM regularization parameter
models = (svm.SVC(kernel='linear', C=C),
          svm.LinearSVC(C=C),
          svm.SVC(kernel='rbf', gamma=0.7, C=C),
          svm.SVC(kernel='poly', degree=3, C=C))
models = (clf.fit(X, y) for clf in models)

# title for the plots
titles = ('SVC with linear kernel',
          'LinearSVC (linear kernel)',
          'SVC with RBF kernel',
          'SVC with polynomial (degree 3) kernel')
# Set-up 2x2 grid for plotting.
fig, sub = plt.subplots(2, 2)
plt.subplots_adjust(wspace=0.4, hspace=0.4)

X0, X1 = X[:, 0], X[:, 1]
xx, yy = make_meshgrid(X0, X1)

for clf, title, ax in zip(models, titles, sub.flatten()):
    plot_contours(ax, clf, xx, yy,
                  cmap=plt.cm.coolwarm, alpha=0.8)
    ax.scatter(X0, X1, c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')
    ax.set_xlim(xx.min(), xx.max())
    ax.set_ylim(yy.min(), yy.max())
    ax.set_xlabel('Sepal length')
    ax.set_ylabel('Sepal width')
    ax.set_xticks(())
    ax.set_yticks(())
    ax.set_title(title)

plt.show()

plt.subplots_adjust(wspace=0.4, hspace=0.4):调整子图间距。(还可以调节上下左右)

zip(models, titles, sub.flatten()):

       zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

sub.flatten():

      将数组拉直成一维。

cmap=plt.cm.coolwarm

     colormap设置。

猜你喜欢

转载自blog.csdn.net/m0_38019841/article/details/84280424