Scikit Learn 简明教程

Scikit Learn - Support Vector Machines

本章讨论了一种称为支持向量机 (SVM) 的机器学习方法。

Introduction

支持向量机 (SVM) 是强大而灵活的监督式机器学习方法,用于分类、回归和异常值检测。SVM 在高维空间中非常高效,通常用于分类问题。SVM 很流行且内存高效,因为它们在决策函数中使用训练点子集。

SVM 的主要目标是将数据集划分为多个类别,以便找到 maximum marginal hyperplane (MMH) ,这可以通过以下两步完成 −

  1. 支持向量机会首先迭代生成超平面,以最佳方式分隔类别。

  2. 之后,它将选择正确隔离类别的超平面。

SVM 中的一些重要概念如下 −

  1. Support Vectors − 它们可以定义为最接近超平面的数据点。支持向量有助于决定分隔线。

  2. Hyperplane − 分隔具有不同类别的对象的集合的决策平面或空间。

  3. Margin − 不同类别最接近数据点上的两条线之间的间隔称为间隔。

以下图表将让您深入了解这些 SVM 概念−

marginal hyperplane

Scikit-learn 中的 SVM 同时支持稀疏和密集样本向量作为输入。

Classification of SVM

Scikit-learn 提供了三个类,即 SVC, NuSVCLinearSVC ,它们可以执行多类分类。

SVC

C 支持向量分类,其实现基于 libsvm 。scikit-learn 使用的模块是 sklearn.svm.SVC 。此类根据一对一方案处理多类支持。

Parameters

下表包含 sklearn.svm.SVC 类使用的参数:

Sr.No

Parameter & Description

1

C - float,可选,默认 = 1.0 它是误差项的惩罚参数。

2

kernel - 字符串,可选,默认 = “rbf” 此参数指定算法中要使用的核类型。我们可以在以下任意一种中进行选择: ‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’ 。核心的默认值是 ‘rbf’

3

degree - int,可选,默认 = 3 它表示“poly”核函数的次数,并且所有其他核将忽略它。

4

gamma - {“scale”、“auto”} 或 float,它是内核“rbf”、“poly”和“sigmoid”的内核系数。

5

optinal default - =“scale” 如果你选择默认值,即 gamma = “scale”,则 SVC 要使用的 gamma 值为 1/(𝑛𝑓𝑒𝑎𝑡𝑢𝑟𝑒𝑠∗𝑋.𝑣𝑎𝑟())。另一方面,如果 gamma = ‘auto’,则使用 1/𝑛𝑓𝑒𝑎𝑡𝑢𝑟𝑒𝑠。

6

coef0 - float,可选,默认 = 0.0 核函数中的独立项,仅在“poly”和“sigmoid”中显着。

7

tol - float,可选,默认 = 1.e-3 此参数表示迭代的停止准则。

8

shrinking - 布尔值,可选,默认 = True 此参数表示我们是否要使用启发式收缩。其默认值为 false。

9

verbose - 布尔值,默认:false 它启用或禁用详细输出。其默认值是 false。

10

probability - 布尔值,可选,默认 = true 此参数启用或禁用概率估计。默认值是 false,但必须在调用拟合之前启用它。

11

max_iter - int,可选,默认 = -1 如名称所示,它表示求解器中迭代的最大次数。值 -1 意味着对迭代次数没有限制。

12

cache_size - float,可选 此参数将指定内核高速缓存的大小。值将以 MB(兆字节)表示。

13

random_state − int, RandomState instance or None, optional, default = none This parameter represents the seed of the pseudo random number generated which is used while shuffling the data. Followings are the options − int − In this case, random_state is the seed used by random number generator. RandomState instance − In this case, random_state is the random number generator. None − In this case, the random number generator is the RandonState instance used by np.random.

14

class_weight - {dict,'balanced'},可选 此参数将针对 SVC 将类 j 的参数 C 设置为 𝑐𝑙𝑎𝑠𝑠_𝑤𝑒𝑖𝑔ℎ𝑡[𝑗]∗𝐶。如果我们使用默认选项,则意味着所有类都被认为具有权重一。另一方面,如果你选择 class_weight:balanced ,则它将使用 y 的值来自动调整权重。

15

decision_function_shape - ovo','ovr',默认 = 'ovr' 此参数将决定算法是否将返回 ‘ovr’ (一对多)与其他所有分类器形状相同的判决函数或 libsvm 的原始 ovo (一对一)判决函数。

16

break_ties - 布尔值,可选,默认 = false True - 预测将根据决策函数的置信度值打破平局 False - 预测将在绑定的类中返回第一个类。

Attributes

下表包含 sklearn.svm.SVC 类使用的属性:

Sr.No

Attributes & Description

1

support_ - 类数组,形状 = [n_SV] 它返回支持向量的索引。

2

support_vectors_ - 与数组类似,形状 = [n_SV, n_features],返回支持向量。

3

n_support_ - 与数组类似,dtype=int32,形状 = [n_class],表示每个类的支持向量数量。

4

dual_coef_ - 数组,形状 = [n_class-1,n_SV],这是决策函数中支持向量的系数。

5

coef_ - 数组,形状 = [n_class * (n_class-1)/2, n_features],此属性仅可用于线性内核,提供分配给特征的权重。

6

intercept_ - 数组,形状 = [n_class * (n_class-1)/2],表示决策函数中的独立项(常数)。

7

fit_status_ - int,如果正确拟合,输出将为 0。如果拟合不正确,输出将为 1。

8

classes_ - 形状 = [n_classes] 的数组,给出类的标签。

Implementation Example

与其他分类器类似,SVC 还必须使用以下两个数组进行拟合 -

  1. 数组 X ,保存训练样本。其大小为 [n_samples, n_features]。

  2. 数组 Y ,保存目标值,即训练样本的类标签。其大小为 [n_samples]。

以下 Python 脚本使用 sklearn.svm.SVC 类 -

import numpy as np
X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
y = np.array([1, 1, 2, 2])
from sklearn.svm import SVC
SVCClf = SVC(kernel = 'linear',gamma = 'scale', shrinking = False,)
SVCClf.fit(X, y)

Output

SVC(C = 1.0, cache_size = 200, class_weight = None, coef0 = 0.0,
   decision_function_shape = 'ovr', degree = 3, gamma = 'scale', kernel = 'linear',
   max_iter = -1, probability = False, random_state = None, shrinking = False,
   tol = 0.001, verbose = False)

Example

现在,一旦拟合,我们可以借助以下 Python 脚本获取权重向量:

SVCClf.coef_

Output

array([[0.5, 0.5]])

Example

同样,我们可以获得其他属性的值,如下所示 -

SVCClf.predict([[-0.5,-0.8]])

Output

array([1])

Example

SVCClf.n_support_

Output

array([1, 1])

Example

SVCClf.support_vectors_

Output

array(
   [
      [-1., -1.],
      [ 1., 1.]
   ]
)

Example

SVCClf.support_

Output

array([0, 2])

Example

SVCClf.intercept_

Output

array([-0.])

Example

SVCClf.fit_status_

Output

0

NuSVC

NuSVC 是核支持向量分类。它是 scikit-learn 提供的用于执行多类分类的另一个类。它类似于 SVC,但 NuSVC 接受略有不同的参数集。与 SVC 不同的参数如下 -

  1. nu - float,可选,默认值 = 0.5

它表示训练误差的上限和支持向量数量的下限。其值应在 (o,1] 区间内。

其他参数和属性与 SVC 相同。

Implementation Example

我们还可以使用 sklearn.svm.NuSVC 类实现相同的示例。

import numpy as np
X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
y = np.array([1, 1, 2, 2])
from sklearn.svm import NuSVC
NuSVCClf = NuSVC(kernel = 'linear',gamma = 'scale', shrinking = False,)
NuSVCClf.fit(X, y)

Output

NuSVC(cache_size = 200, class_weight = None, coef0 = 0.0,
   decision_function_shape = 'ovr', degree = 3, gamma = 'scale', kernel = 'linear',
   max_iter = -1, nu = 0.5, probability = False, random_state = None,
   shrinking = False, tol = 0.001, verbose = False)

我们可以像使用 SVC 一样获得其余属性的输出。

LinearSVC

它就是线性支持向量分类。它类似于 SVC,其 kernel = ‘linear’。它们之间的区别在于 LinearSVC 根据 liblinear 实现,而 SVC 根据 libsvm 实现。这就是 LinearSVC 在惩罚和损失函数的选择方面具有更大灵活性的原因。它的可扩展性也更高,适用于大量样本。

如果我们讨论其参数和属性,那么它不支持 ‘kernel’ ,因为它假定为线性,并且还缺少 support_, support_vectors_, n_support_, fit_status_dual_coef_ 等属性。

不过,它支持 penaltyloss 参数,如下所示:

  1. penalty − string, L1 or L2(default = ‘L2’) 此参数用于指定罚则(正则化)中使用的范数(L1 或 L2)。

  2. loss − string, hinge, squared_hinge (default = squared_hinge) 它代表损失函数,其中“铰链”是标准 SVM 损失,“平方铰链”是铰链损失的平方。

Implementation Example

以下 Python 脚本使用 sklearn.svm.LinearSVC 类:

from sklearn.svm import LinearSVC
from sklearn.datasets import make_classification
X, y = make_classification(n_features = 4, random_state = 0)
LSVCClf = LinearSVC(dual = False, random_state = 0, penalty = 'l1',tol = 1e-5)
LSVCClf.fit(X, y)

Output

LinearSVC(C = 1.0, class_weight = None, dual = False, fit_intercept = True,
   intercept_scaling = 1, loss = 'squared_hinge', max_iter = 1000,
   multi_class = 'ovr', penalty = 'l1', random_state = 0, tol = 1e-05, verbose = 0)

Example

现在,在拟合模型后,可以预测新值如下所示:

LSVCClf.predict([[0,0,0,0]])

Output

[1]

Example

对于上述示例,我们可以借助以下 Python 脚本获取权重向量:

LSVCClf.coef_

Output

[[0. 0. 0.91214955 0.22630686]]

Example

同样,我们可以借助以下 Python 脚本获取截距值:

LSVCClf.intercept_

Output

[0.26860518]

Regression with SVM

如前所述,SVM 用于分类和回归问题。Scikit-learn 的支持向量分类 (SVC) 方法还可以扩展以解决回归问题。该扩展方法称为支持向量回归 (SVR)。

Basic similarity between SVM and SVR

由 SVC 创建的模型仅取决于训练数据的一个子集。为什么?因为用于构建模型的成本函数不关心位于裕度之外的训练数据点。

然而,由 SVR(支持向量回归)生成的模型也仅取决于训练数据的一个子集。为什么?因为用于构建模型的成本函数会忽略任何接近模型预测的训练数据点。

Scikit-learn 提供了三个类,即 SVR, NuSVR and LinearSVR ,作为 SVR 的三个不同实现。

SVR

它是基于 libsvm 实现的 Epsilon 支持向量回归。与 SVC 相反,该模型中有两个自由参数,即 ‘C’‘epsilon’

  1. epsilon − float,可选,默认 = 0.1

它表示 epsilon-SVR 模型中的 epsilon,并指定 epsilon 管,在该管中,损失函数中与实际值距离 epsilon 之内的预测点不会产生罚则。

其他参数和属性与我们在 SVC 中使用的类似。

Implementation Example

以下 Python 脚本使用 sklearn.svm.SVR 类:

from sklearn import svm
X = [[1, 1], [2, 2]]
y = [1, 2]
SVRReg = svm.SVR(kernel = ’linear’, gamma = ’auto’)
SVRReg.fit(X, y)

Output

SVR(C = 1.0, cache_size = 200, coef0 = 0.0, degree = 3, epsilon = 0.1, gamma = 'auto',
   kernel = 'linear', max_iter = -1, shrinking = True, tol = 0.001, verbose = False)

Example

现在,一旦拟合,我们可以借助以下 Python 脚本获取权重向量:

SVRReg.coef_

Output

array([[0.4, 0.4]])

Example

同样,我们可以获得其他属性的值,如下所示 -

SVRReg.predict([[1,1]])

Output

array([1.1])

同样,我们还可以获得其他属性的值。

NuSVR

NuSVR 是 Nu 支持向量回归。它类似于 NuSVC,但 NuSVR 使用参数 nu 来控制支持向量的数量。此外,与 NuSVC 不同(其中 nu 替换了 C 参数),这里它替换了 epsilon

Implementation Example

以下 Python 脚本使用 sklearn.svm.SVR 类:

from sklearn.svm import NuSVR
import numpy as np
n_samples, n_features = 20, 15
np.random.seed(0)
y = np.random.randn(n_samples)
X = np.random.randn(n_samples, n_features)
NuSVRReg = NuSVR(kernel = 'linear', gamma = 'auto',C = 1.0, nu = 0.1)^M
NuSVRReg.fit(X, y)

Output

NuSVR(C = 1.0, cache_size = 200, coef0 = 0.0, degree = 3, gamma = 'auto',
   kernel = 'linear', max_iter = -1, nu = 0.1, shrinking = True, tol = 0.001,
   verbose = False)

Example

现在,一旦拟合,我们可以借助以下 Python 脚本获取权重向量:

NuSVRReg.coef_

Output

array(
   [
      [-0.14904483, 0.04596145, 0.22605216, -0.08125403, 0.06564533,
      0.01104285, 0.04068767, 0.2918337 , -0.13473211, 0.36006765,
      -0.2185713 , -0.31836476, -0.03048429, 0.16102126, -0.29317051]
   ]
)

同样,我们还可以获得其他属性的值。

LinearSVR

它是线性支持向量回归。它类似于 SVR(kernel =“linear”)。它们之间的区别在于, LinearSVR 是根据 liblinear 实现的,而 SVC 是根据 libsvm 实现的。这就是为什么 LinearSVR 在罚则和损失函数的选择上更灵活的原因。它也能更好地扩展到大量样本。

如果我们讨论其参数和属性,那么它不支持 ‘kernel’ ,因为它假定为线性,并且还缺少 support_, support_vectors_, n_support_, fit_status_dual_coef_ 等属性。

不过,它支持以下“损失”参数:

  1. loss - 字符串,可选,默认 = ‘epsilon_insensitive’

它表示 epsilon_insensitive 损失为 L1 损失且平方 epsilon_insensitive 损失为 L2 损失的损失函数。

Implementation Example

以下 Python 脚本使用 sklearn.svm.LinearSVR 类 -

from sklearn.svm import LinearSVR
from sklearn.datasets import make_regression
X, y = make_regression(n_features = 4, random_state = 0)
LSVRReg = LinearSVR(dual = False, random_state = 0,
loss = 'squared_epsilon_insensitive',tol = 1e-5)
LSVRReg.fit(X, y)

Output

LinearSVR(
   C=1.0, dual=False, epsilon=0.0, fit_intercept=True,
   intercept_scaling=1.0, loss='squared_epsilon_insensitive',
   max_iter=1000, random_state=0, tol=1e-05, verbose=0
)

Example

现在,在拟合模型后,可以预测新值如下所示:

LSRReg.predict([[0,0,0,0]])

Output

array([-0.01041416])

Example

对于上述示例,我们可以借助以下 Python 脚本获取权重向量:

LSRReg.coef_

Output

array([20.47354746, 34.08619401, 67.23189022, 87.47017787])

Example

同样,我们可以借助以下 Python 脚本获取截距值:

LSRReg.intercept_

Output

array([-0.01041416])