-
2021-11-23 22:28:21
目录
1. 前言
- 转载请注明出处
- 文章中有一部分内容是个人理解,所以内容仅供参考
- 这篇文章是讲解sklearn库中SVM部分中SVC这一API.
- 关于实战部分可以参考这篇文章(有源码,可直接运行):【Sklearn】【实战】【SVM】乳腺癌检测,模拟线上部署(1)
- 这里是官方说明文档传送门:sklearn.svm.SVC
- 本文约7000字,阅读完毕大约需要10分钟
- 本文可当做开发时的开发手册作为参考,建议收藏
2. 简介
- SVC为Support Vector Classification的简写,顾名思义,其是基于支持向量的分类器
- SVC是基于libsvm实现的
- SVC的拟合时间是和样本数量呈二次方指数关系,因此这一分类模型适用于样本较小情况,如果样本数量过大(超过1W),建议使用其他模型,例如
LinearSVC
或者SGDClassifier
3. 语法
3.1 API形式
- 形式如下,里面的参数均为默认参数
SVC( C=1.0, kernel='rbf', degree=3, gamma='scale', coef0=0.0, shrinking=True, probability=False, tol=0.001, cache_size=200, class_weight=None, verbose=False, max_iter=- 1, decision_function_shape='ovr', break_ties=False, random_state=None)
3.2 参数说明
参数 名称 数据 作用 C 正则化系数 float类型,默认值为1.0 1. 正则化的强度与C的大小成反比,且必须为正。
2. 主要是用来防止模型过拟合
3. C值越大,对模型的惩罚越高,泛化能力越弱(过拟合)
4. 反之,C值越小,对模型的惩罚越低,泛化能力越强(欠拟合)kernel 核函数 1. string类型
2. {‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’}
3. 默认值为’rbf’1. 用来选择映射到高维线性可分的核函数
2. linear: 线性核函数; 优点: 简单、运算效率高;缺点: 对线性不可分的数据集没有很好的效果
3. ploy: 多项式核函数; 优点: 可以拟合出复杂的分割超平面;缺点: 有三个参数,调参困难,且当n过大时,模型拟合时间会很长 ;
4. rbf: 径向基函数 通常定义为样本到数据中心之间径向距离(通常是欧氏距离)的单调函数(由于距离是径向同性的); 相较于多项式核,具有参数少的优点
5. sigmoid:Logistic函数 也称为S型生长曲线,优点:平滑
6. precomputed:预训练好的核函数对应的Gram 矩阵 优点: 不用再次拟合核函数对应的Gram 矩阵,直接进行映射就可以了degree 多项式核函数的维度 1. int类型,默认值为3 1. 只有在使用多项式核函数的时候才有用,使用其他核函数自动忽略此参数
2. 用来确定多项式核函数的维度,即n的值gamma ‘rbf’, ‘poly’ 和‘sigmoid’ 核函数的系数 1. string类型,默认值为‘scale’
2. {‘auto’, ‘scale’}1. auto: gamma = 1 / n_features
2. scale: gamma = 1 / (n_features * X.var())
3. 只作用于 rbf, poly,sigmoid 三个核函数coef0 常数项 1. float类型,默认值为0 1. 只作用于poly 和 sigmoid 核函数
2. 作用相当于是对核函数映射的结果进行一个移位操作shrinking 启用启发式收缩 1. bool类型,默认为True 1. 是否采用启发式收缩,当迭代次数过大时, 启用启发式收缩可以缩短训练时间,然而如果我们对停止迭代容忍度较高时(tol参数来反映),不用启发式收缩可能会更快一些 probability 启用概率估计 1. bool类型,默认为False 1. 在拟合(fit)模型之前启用
2. 启用之后会减缓拟合速度,但是拟合之后,模型能够输出各个类别对应的概率tol 停止拟合容忍度 1. float类型,默认值为1e-3 即为0.001 1. 定义模型停止拟合的误差值 cache_size 核缓存大小 1. float类型,默认值为200(MB) 1. 指定模型在训练时,能占用的最大RAM空间(PS. 经过实验,当大小设置超过2000MB时,训练时长反而会增加,这应该是一个BUG),在2000MB以内,不超过其所需最大内存,则不会降低训练速度,也不会增加。
2. 所以训练多采用的数据集维度越高,条数越高,当所需内存超出了,我们可以通过调整cache_size 的大小来加快模型拟合class_weight 类别的权重 1. 字典,默认值为None
2. {dict} or ‘balanced’1. 该参数表示给每个类别分别设置不同的惩罚参数C
2. 如果没有给,则会给所有类别都给C=1,即前面参数指出的参数C
3. 如果给定参数‘balance’,自动调整权重 C = n_samples / (n_classes * np.bincount(y)) 其中y为每个训练数据的标签值verbose 启用详细输出 1. bool类型,默认值:False 1. 该参数表示日志是否启用详细输出,会输出iter次数,nSV等参数的值
2. 如果启用,可能会导致无法进行多线程工作,降低拟合速率max_iter 最大迭代次数 1. int类型,默认值: -1 1. 硬性设置最大迭代次数,不管模型是否拟合完成,即不关心误差值(tol参数)
2. 设置-1的话,意味着不限制迭代次数,即按照误差值来停止模型拟合decision_function_shape 多分类策略 1. 字典类型 ,默认值: ‘ovr’ 1. 设置进行多分类任务时,采用的分类策略
2. 当进行二分类任务时,这一参数被自动忽略break_ties 启用打破平局 1. bool类型,默认值为Flase 1. 当进行多分类任务时可以启用
2. 启用后,多分类策略会被设置为 ovr
3. 作用在于,当两个类别具有相同的分类概率时,则根据类名排序,返回第一个类,如果启用之后,则会根据decision_function的置信度来决定返回的类
4. 启用之后,会增加计算开销,降低拟合好后的模型预测效率random_state 随机数 1. int类型,默认值:None 1. 控制伪随机数生成,保证多次训练时,打乱的数据是一致的,从而进行概率估计。2. 当 probability 设置 False时,这一参数被自动忽略 3.3 属性说明
属性 名称 数据 作用 class_weight 各类权重 1. ndarray,一维数组,(n_classes, ) 1. 用来获取模型对各个类别设置的权重,与参数中的class_weight相关
2. 数组长度为类别数,内容为每个类的权重classes_ 类别 1. ndarray,一维数组 ,(n_classes, ) 1. 用来获取各个类别的标签
2. 数组的长度为类别数,内容为每个类对应的标签coef_ 特征权重向量 1. ndarray,二维数组,(n_classes * (n_classes - 1) / 2, n_features) 1. 获取特征权重向量
2. 当核函数为linear时,才可以调用这一属性dual_coef_ 对偶系数 1. ndarray,二维数组,(n_classes -1, n_SV) 1. decision_funciton 中的支持向量的对偶系数
2. n_SV 为支持向量的个数
3. 所有 ovo 分类器的系数fit_status_ 拟合状态 1. int类型 1. 拟合成功0, 否则为1,进行告警 intercept_ 决策函数常量 1. ndarray,一维数组, (n_classes * (n_classes - 1) / 2, ) 1. decision_funciton 中的常量 n_features_in_ 特征数量 1. int类型 1. 拟合过程中使用到的特征数量 feature_names_in_ 特征名称 1. ndarray,一维数组,(n_features_in_,) 1. 获取拟合时特征的名称 support_ 支持向量索引 1. ndarray,一维数组, (n_SV,) 1. 获取模型拟合后获得的所有支持向量的索引 support_vectors_ 支持向量 1. ndarray,二维数组,(n_SV, n_features) 1. 获取所有的支持向量 n_support_ 每类的支持向量数 1. ndarray,一维数组 ,(n_classes,), dtype=int32 1. 获取每种类别的支持向量数 probA_ platt scaling系数A 1. ndarray, 一维数组, (n_classes * (n_classes - 1) / 2, ) 1. 只有当 probability=True.时,这一系数A才会被计算 ,probability=False,则为空数组。 probB_ platt scaling纠正项B 1. ndarray, 一维数组, (n_classes * (n_classes - 1) / 2, ) 1. 只有当 probability=True.时,这一纠正项B才会被计算,probability=False,则为空数组。 shape_fit_ 训练向量维度数 1.元组,(n_dimensions_of_X,) 1. 训练向量X的数组维度 4. 方法说明
4.1 decision_function(X)
1. 描述: 计算所有样本X的决策函数
2. 参数: X为所有样本组成的二维数组,大小为(n_samples, n_features)
3. 返回值: 返回模型中每个类的样本决策函数,大小为 (n_samples, n_classes * (n_classes-1) / 2)
4. 注意: 如果decision_function_shape =“ ovr”,则返回值的大小为(n_samples,n_classes)4.2 fit(X, y, sample_weight=None)
1. 描述: 用训练数据拟合模型
2. 参数: X: 训练数据; y: 训练数据标签; sample_weight: 每个样本的权重,(n_samples,)
3. 返回值: 自身,拟合好的模型
4. 注意: 无4.3 get_params(deep=True)
1. 描述: 获取模型的所有参数
2. 参数: 如果为真,则将返回此模型和作为模型的所包含子对象的参数
3. 返回值: 字典类型, 所有的参数
4. 注意: 无4.4 predict(X)
1. 描述: 用拟合好的模型对所有样本X进行预测
2. 参数: 所有预测样本,二维数组(n_samples, n_features)
3. 返回值: 所有预测 X的预测标签,一维数组,(n_sample, )
4. 注意: 无4.5 predict_log_proba(X)
1. 描述: 计算所有预测样本在每个类别上的对数概率
2. 参数: 所有预测样本,二维数组(n_samples, n_features)
3. 返回值: 返回模型中每个类的样本的对数概率,二维数组,(n_samples, n_classes)
4. 注意: 在模型训练时,需要将 probability参数设置为True,才能使用此方法4.6 predict_proba(X)
1. 描述: 计算所有预测样本在每个类别上的概率
2. 参数: 所有预测样本,二维数组(n_samples, n_features)
3. 返回值: 返回模型中每个类的样本的对数概率,二维数组,(n_samples, n_classes)
4. 注意: 在模型训练时,需要将 probability参数设置为True,才能使用此方法4.7 score(X, y, sample_weight=None)
1. 描述: 返回给定测试数据上的平均准确度
2. 参数: X: 训练数据; y: 训练数据标签; sample_weight: 每个样本的权重,(n_samples,)
3. 返回值: 浮点类型,平均准确度
4. 注意: 无4.8 set_params(**params)
1. 描述: 重置当前模型的参数
2. 参数: 字典类型,内容为当前模型的参数
3. 返回值: 重置参数后的模型
4. 注意: 无5. 总结
不知不觉六个小时已经过去了,这会儿已经凌晨四点了。本以为这篇文章两个小时就能结束。无奈中间遇到了一个又一个不懂的知识点,整个过程就像升级打怪一样,在整理整个API的过程中,个人对模型的理解更深刻了,颇有收获。
有时间再继续往下更新~
希望这篇文档能对各位看官产生一定的帮助, 如有不妥,欢迎评论区指正~
6. 参考资料
更多相关内容 -
sklearn.svm.SVC()函数解析
2021-07-31 00:43:24sklearn.svm.SVC()函数解析 class sklearn.svm.SVC(C=1.0, kernel=’rbf’, degree=3, gamma=’auto_deprecated’, coef0=0.0, shrinking=True, probability=False, tol=0.001, cache_size=200, class_weight=None,...sklearn.svm.SVC()函数解析
class sklearn.svm.SVC(C=1.0, kernel=’rbf’, degree=3, gamma=’auto_deprecated’,
coef0=0.0, shrinking=True, probability=False, tol=0.001,
cache_size=200, class_weight=None, verbose=False, max_iter=-1,
decision_function_shape=’ovr’, random_state=None)C
:惩罚项参数,C越大, 对误分类的惩罚越大(泛化能力越弱)kernel
:核函数类型- ‘linear’:线性核函数 < x , x " > <x,x^"> <x,x">
- ‘poly’:多项式核函数 ( γ < x , x " > + c o e f 0 ) d (γ<x,x^">+coef0)^d (γ<x,x">+coef0)d, 其中d是有参数degree指定
- ‘rbf’: 高斯核函数 e x p ( − γ ∣ ∣ x − x " ∣ ∣ exp(-γ||x-x^"|| exp(−γ∣∣x−x"∣∣,其中γ是由参数gamma指定,必须大于0
- ‘sigmoid’: sigmod核函数 t a n h ( g a m m a ∗ < x , x " > + c o e f 0 ) tanh(gamma*<x,x^">+coef0) tanh(gamma∗<x,x">+coef0)
degree
:多项式核函数的阶数.gamma
: 核函数系数,默认为auto(代表其值为样本特征数的倒数), 只对’rbf’,‘poly’,'sigmod’有效.定义了单个训练样本有多大的影响力.一个大的gamma,其附近的其他样本一定会被影响到.class_weight
:{dict,‘balanced’},可选类别权重.decision_function_shape
:‘ovo’(默认,one vs one),‘ovr’(one vs reset).
使用技巧
支持向量机不能很好的容忍非标准化数据,所以强烈建议先将数据标准化后在训练.
数学公式
支持向量机在高维或无限维空间中构造平面或超平面集,可用于分类,回归或其他任务.
一个好的分离的实现方案是,超平面距离训练数据中任意一类的样本的距离达到最大(也称为函数间距)
下图显示一个线性可分问题的决策函数,边界有三个样本,称为"支持向量"
SVC
给定训练样本 x i ∈ R p , i = 1 , . . . , n x_i\in R^p,i=1,...,n xi∈Rp,i=1,...,n在二分类中, 和一个向量 y ∈ { 1 , − 1 } n y\in {\{1,-1\}}^n y∈{1,−1}n,我们的目标是找到 w ∈ R p w \in R^p w∈Rp和 b ∈ R b \in R b∈R对于给定的预测
sign ( w T ϕ ( x ) + b ) \operatorname{sign}\left(w^{T} \phi(x)+b\right) sign(wTϕ(x)+b)
对大多数样本判断正确.SVC主要解决以下问题
min w , b , ζ 1 2 w T w + C ∑ i = 1 n ζ i subject to y i ( w T ϕ ( x i ) + b ) ≥ 1 − ζ i ζ i ≥ 0 , i = 1 , … , n \min _{w, b, \zeta} \frac{1}{2} w^{T} w+C \sum_{i=1}^{n} \zeta_{i} \\ \text { subject to } y_{i}\left(w^{T} \phi\left(x_{i}\right)+b\right) \geq 1-\zeta_{i} \zeta_{i} \geq 0, i=1, \ldots, n w,b,ζmin21wTw+Ci=1∑nζi subject to yi(wTϕ(xi)+b)≥1−ζiζi≥0,i=1,…,n
要最大化间距(等价于最小化 ∣ ∣ w ∣ ∣ 2 = w T w ||w||^2=w^Tw ∣∣w∣∣2=wTw),同时对于分类错误的样本或者在间距内部的样本会招致惩罚.理想情况下, 对于所有样本来说 y i ( w T ϕ ( x i ) + b ) y_{i}\left(w^{T} \phi\left(x_{i}\right)+b\right) yi(wTϕ(xi)+b)的值都应该>1,这是完美预测. 若不能与超平面完全分离,允许一些样本离他们正确的边缘有一个距离 ζ i \zeta_{i} ζi. 惩罚项 C C C控制这个惩罚强度.
对原始问题的对偶问题
min α 1 2 α T Q α − e T α subject to y T α = 0 0 ≤ α i ≤ C , i = 1 , … , n \min _{\alpha} \frac{1}{2} \alpha^{T} Q \alpha-e^{T} \alpha \\ \text { subject to } y^{T} \alpha=0 \\ 0 \leq \alpha_{i} \leq C, i=1, \ldots, n αmin21αTQα−eTα subject to yTα=00≤αi≤C,i=1,…,n
其中e是一个全1向量, Q Q Q是一个n*n的半正定矩阵
Q i j ≡ y i y j K ( x i , x j ) K ( x i , x j ) = ϕ ( x i ) T ϕ ( x j ) Q_{i j} \equiv y_{i} y_{j} K\left(x_{i}, x_{j}\right) \\ K\left(x_{i}, x_{j}\right)=\phi\left(x_{i}\right)^{T} \phi\left(x_{j}\right) Qij≡yiyjK(xi,xj)K(xi,xj)=ϕ(xi)Tϕ(xj)K ( x i , x j ) K\left(x_{i}, x_{j}\right) K(xi,xj)是内核. a i a_i ai成为对称系数,他们的上界是 C C C.这种对偶形式强调这样一个事实, 即训练向量可通过核函数隐式映射到一个更高维空间.
决策函数
一旦优化问题解决,对于给定的样本 x x x的决策函数的输出将变成:
∑ i ∈ S V y i α i K ( x i , x ) + b \sum_{i \in S V} y_{i} \alpha_{i} K\left(x_{i}, x\right)+b i∈SV∑yiαiK(xi,x)+b预测的类对应于它的符号. 我们只需在支持向量(即位于边缘范围内的样本上)求和,因为对于其他样本,对偶系数 a i a_i ai为0
属性
可以通过以下属性访问这些参数
dual_coef_
: y i a i y_ia_i yiaisupport_vectors_
:访问支持向量intercept_
: 访问截距下 b b b
实例
#导入库 import numpy as np from sklearn.svm import SVC from sklearn.datasets import make_blobs
# 创建分割数据 X,y = make_blobs(n_samples=40, centers=2, random_state=1) print("X:{}, y:{}".format(X.shape,y.shape))
X:(40, 2), y:(40,)
clf = SVC(gamma='auto') clf.fit(X,y) print(clf.predict([[0.8,1]]))
[0]
# 探索建好的模型 clf.predict(X)#根据决策边界, 对X中的样本进行分类,返回的结构为n_samples
array([1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0])
clf.score(X,y)#返回给定测试数据和target的平均准确度
1.0
clf.support_vectors_#返回支持向量
array([[-7.94152277e-01, 2.10495117e+00], [-2.18773166e+00, 3.33352125e+00], [ 2.42271161e-04, 5.14853403e+00], [-2.77687025e+00, 4.64090557e+00], [-1.61734616e+00, 4.98930508e+00], [-1.97451969e-01, 2.34634916e+00], [ 8.52518583e-02, 3.64528297e+00], [-2.76017908e+00, 5.55121358e+00], [-2.34673261e+00, 3.56128423e+00], [-8.86608312e+00, -2.43353173e+00], [-9.68207756e+00, -5.97554976e+00], [-9.50919436e+00, -4.02892026e+00], [-9.80679702e+00, -1.85309341e+00], [-1.14418263e+01, -4.45781441e+00], [-7.81213710e+00, -5.34984488e+00], [-1.07448708e+01, -2.26089395e+00]])
参考
-
python SVM 案例,sklearn.svm.SVC 参数说明
2020-12-10 22:32:39sklearn.svm.SVC 参数说明经常用到sklearn中的SVC函数,这里把文档中的参数翻译了一些,以备不时之需。本身这个函数也是基于libsvm实现的,所以在参数设置上有很多相似的地方。(PS: libsvm中的二次规划问题的解决...sklearn.svm.SVC 参数说明
经常用到sklearn中的SVC函数,这里把文档中的参数翻译了一些,以备不时之需。
本身这个函数也是基于libsvm实现的,所以在参数设置上有很多相似的地方。(PS: libsvm中的二次规划问题的解决算法是SMO)。sklearn.svm.SVC(C=1.0,kernel='rbf', degree=3, gamma='auto',coef0=0.0,shrinking=True,probability=False,tol=0.001,cache_size=200, class_weight=None,verbose=False,max_iter=-1,decision_function_shape=None,random_state=None)
参数:
l C:C-SVC的惩罚参数C?默认值是1.0
C越大,相当于惩罚松弛变量,希望松弛变量接近0,即对误分类的惩罚增大,趋向于对训练集全分对的情况,这样对训练集测试时准确率很高,但泛化能力弱。C值小,对误分类的惩罚减小,允许容错,将他们当成噪声点,泛化能力较强。
l kernel :核函数,默认是rbf,可以是‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’
0 – 线性:u’v
1 – 多项式:(gamma*u’*v + coef0)^degree
2 – RBF函数:exp(-gamma|u-v|^2)
3 –sigmoid:tanh(gamma*u’*v + coef0)
l degree :多项式poly函数的维度,默认是3,选择其他核函数时会被忽略。
l gamma : ‘rbf’,‘poly’ 和‘sigmoid’的核函数参数。默认是’auto’,则会选择1/n_features
l coef0 :核函数的常数项。对于‘poly’和 ‘sigmoid’有用。
l probability :是否采用概率估计?.默认为False
l shrinking :是否采用shrinking heuristic方法,默认为true
l tol :停止训练的误差值大小,默认为1e-3
l cache_size :核函数cache缓存大小,默认为200
l class_weight :类别的权重,字典形式传递。设置第几类的参数C为weight*C(C-SVC中的C)
l verbose :允许冗余输出?
l max_iter :最大迭代次数。-1为无限制。
l decision_function_shape :‘ovo’, ‘ovr’ or None, default=None3
l random_state :数据洗牌时的种子值,int值
主要调节的参数有:C、kernel、degree、gamma、coef0。
案例代码:#!/usr/bin/python# -*- coding:utf-8 -*-import numpy as npfrom sklearn import svmfrom scipy import statsfrom sklearn.metrics import accuracy_scoreimport matplotlib as mplimport matplotlib.pyplot as plt#设置画图过程中,图像的最小值 与最大值取值def extend(a, b, r):
x = a - b
m = (a + b) / 2
return m-r*x/2, m+r*x/2if __name__ == "__main__":
np.random.seed(0)
N = 20
x = np.empty((4*N, 2))
print("{}\n{}".format(x.shape,x))
means = [(-1, 1), (1, 1), (1, -1), (-1, -1)]
print(means)
sigmas = [np.eye(2), 2*np.eye(2), np.diag((1,2)), np.array(((2,1),(1,2)))]
print(sigmas) for i in range(4):
mn = stats.multivariate_normal(means[i], sigmas[i]*0.3) # print(mn)
x[i*N:(i+1)*N, :] = mn.rvs(N) # print(mn.rvs(N))
a = np.array((0,1,2,3)).reshape((-1, 1))
print(a)
y = np.tile(a, N).flatten()
print(np.tile(a, N) )
print(y)
clf = svm.SVC(C=1, kernel='rbf', gamma=1, decision_function_shape='ovo') # clf = svm.SVC(C=1, kernel='linear', decision_function_shape='ovr')
clf.fit(x, y)
y_hat = clf.predict(x)
acc = accuracy_score(y, y_hat)
np.set_printoptions(suppress=True) print (u'预测正确的样本个数:%d,正确率:%.2f%%' % (round(acc*4*N), 100*acc)) # decision_function
print (clf.decision_function(x)) print (y_hat)
x1_min, x2_min = np.min(x, axis=0)
x1_max, x2_max = np.max(x, axis=0)
x1_min, x1_max = extend(x1_min, x1_max, 1.05)
x2_min, x2_max = extend(x2_min, x2_max, 1.05)
x1, x2 = np.mgrid[x1_min:x1_max:500j, x2_min:x2_max:500j]
x_test = np.stack((x1.flat, x2.flat), axis=1)
y_test = clf.predict(x_test)
y_test = y_test.reshape(x1.shape)
cm_light = mpl.colors.ListedColormap(['#FF8080', '#A0FFA0', '#6060FF', '#F080F0'])
cm_dark = mpl.colors.ListedColormap(['r', 'g', 'b', 'm'])
mpl.rcParams['font.sans-serif'] = [u'SimHei']
mpl.rcParams['axes.unicode_minus'] = False
plt.figure(facecolor='w')
plt.pcolormesh(x1, x2, y_test, cmap=cm_light)
plt.scatter(x[:, 0], x[:, 1], s=40, c=y, cmap=cm_dark, alpha=0.7)
plt.xlim((x1_min, x1_max))
plt.ylim((x2_min, x2_max))
plt.grid(b=True)
plt.tight_layout(pad=2.5)
plt.title(u'SVM多分类方法:One/One or One/Other', fontsize=18)
plt.show()
分类结果:
-
sklearn.svm.SVC
2019-07-18 01:09:49sklearn.svm.SVC class sklearn.svm.SVC(C = 1.0,kernel ='rbf', degree = 3,gamma ='auto_deprecated', coef0 = 0.0,shrinking = True, probability = False,tol = 0.001, cache_...sklearn.svm.SVC
class sklearn.svm.SVC(C = 1.0,kernel ='rbf', degree = 3,gamma ='auto_deprecated', coef0 = 0.0,shrinking = True, probability = False,tol = 0.001, cache_size = 200,class_weight = None, verbose = False,max_iter = -1, decision_function_shape =' ovr ',random_state =None)
参数:
C : float,可选(默认值= 1.0) 错误术语的惩罚参数C.kernel : string,optional(default =‘rbf’),指定要在算法中使用的内核类型。它必须是’linear’,‘poly’,‘rbf’,‘sigmoid’,‘precomputed’或者callable之一。如果没有给出,将使用’rbf’。如果给出可调用,则它用于从数据矩阵预先计算内核矩阵;
该矩阵应该是一个形状的数组。(n_samples, n_samples)度 : int,可选(默认= 3) 多项式核函数的次数(‘poly’)。被所有其他内核忽略。
gamma : float,optional(默认=‘auto’) ‘rbf’,'poly’和’sigmoid’的核系数。
当前默认值为’auto’,它使用1 / n_features,如果gamma=‘scale’传递,则使用1 /(n_features *
X.var())作为gamma的值。当前默认的gamma’‘auto’将在版本0.22中更改为’scale’。‘auto_deprecated’,不推荐使用’auto’版本作为默认值,表示没有传递明确的gamma值。coef0 : float,optional(默认值= 0.0) 核函数中的独立项。它只在’poly’和’sigmoid’中很重要。
收缩 : 布尔值,可选(默认= True) 是否使用收缩启发式。
概率 : 布尔值,可选(默认=假) 是否启用概率估计。必须在调用之前启用它fit,并且会减慢该方法的速度。
tol : float,optional(默认值= 1e-3) 容忍停止标准。
cache_size : float,可选 指定内核缓存的大小(以MB为单位)。
class_weight : {dict,‘balanced’},可选。
将类i的参数C设置为SVC的class_weight [i] *C. 如果没有给出,所有课程都应该有一个重量。“平衡”模式使用y的值自动调整与输入数据中的类频率成反比的权重n_samples /(n_classes * np.bincount(y))详细说明 : bool,默认值:False
启用详细输出。请注意,此设置利用libsvm中的每进程运行时设置,如果启用,则可能无法在多线程上下文中正常运行。max_iter : int,optional(默认值= -1) 求解器内迭代的硬限制,或无限制的-1。
decision_function_shape : ‘ovo’,‘ovr’,默认=‘ovr’
是否将形状(n_samples,n_classes)的one-vs-rest(‘ovr’)决策函数作为所有其他分类器返回,或者返回具有形状的libsvm的原始one-vs-one(‘ovo’)决策函数(n_samples)
,n_classes *(n_classes - 1)/ 2)。但是,一对一(‘ovo’)总是被用作多级策略。在版本0.19中更改: decision_function_shape默认为’ovr’。
版本0.17中的新功能:建议使用decision_function_shape =‘ovr’。
更改版本0.17:已弃用decision_function_shape ='ovo’且无。
random_state : int,RandomState实例或None,可选(默认=无)
伪随机数生成器的种子在对数据进行混洗以用于概率估计时使用。如果是int,则random_state是随机数生成器使用的种子;
如果是RandomState实例,则random_state是随机数生成器;
如果为None,则随机数生成器是由其使用的RandomState实例np.random。>>> 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 >>> clf = SVC(gamma='auto') >>> clf.fit(X,y) SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, decision_function_shape='ovr', degree=3, gamma='auto', kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False) >>> print(clf.predict([[-0.8, -1]])) [1] >>>
decision_function(self, X)
评估X中样本的决策函数。
fit(self, X, y[, sample_weight])
根据给定的训练数据拟合SVM模型。
get_params(self[, deep])
获取此估算工具的参数。
predict(self, X)
对X中的样本进行分类。
score(self, X, y[, sample_weight])
返回给定测试数据和标签的平均精度。
set_params(self, \*\*params)
设置此估算器的参数。示例一:多标签分类
通过投影到PCA和CCA找到的前两个主要组件以进行可视化目的,然后使用sklearn.multiclass.OneVsRestClassifier具有线性内核的两个SVC
的元分类器来学习每个类的判别模型来执行分类。请注意,PCA用于执行无监督降维,而CCA用于执行监督降维。print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_multilabel_classification from sklearn.multiclass import OneVsRestClassifier from sklearn.svm import SVC from sklearn.decomposition import PCA from sklearn.cross_decomposition import CCA def plot_hyperplane(clf, min_x, max_x, linestyle, label): # get the separating hyperplane w = clf.coef_[0] a = -w[0] / w[1] xx = np.linspace(min_x - 5, max_x + 5) # make sure the line is long enough yy = a * xx - (clf.intercept_[0]) / w[1] plt.plot(xx, yy, linestyle, label=label) def plot_subfigure(X, Y, subplot, title, transform): if transform == "pca": X = PCA(n_components=2).fit_transform(X) elif transform == "cca": X = CCA(n_components=2).fit(X, Y).transform(X) else: raise ValueError min_x = np.min(X[:, 0]) max_x = np.max(X[:, 0]) min_y = np.min(X[:, 1]) max_y = np.max(X[:, 1]) classif = OneVsRestClassifier(SVC(kernel='linear')) classif.fit(X, Y) plt.subplot(2, 2, subplot) plt.title(title) zero_class = np.where(Y[:, 0]) one_class = np.where(Y[:, 1]) plt.scatter(X[:, 0], X[:, 1], s=40, c='gray', edgecolors=(0, 0, 0)) plt.scatter(X[zero_class, 0], X[zero_class, 1], s=160, edgecolors='b', facecolors='none', linewidths=2, label='Class 1') plt.scatter(X[one_class, 0], X[one_class, 1], s=80, edgecolors='orange', facecolors='none', linewidths=2, label='Class 2') plot_hyperplane(classif.estimators_[0], min_x, max_x, 'k--', 'Boundary\nfor class 1') plot_hyperplane(classif.estimators_[1], min_x, max_x, 'k-.', 'Boundary\nfor class 2') plt.xticks(()) plt.yticks(()) plt.xlim(min_x - .5 * max_x, max_x + .5 * max_x) plt.ylim(min_y - .5 * max_y, max_y + .5 * max_y) if subplot == 2: plt.xlabel('First principal component') plt.ylabel('Second principal component') plt.legend(loc="upper left") plt.figure(figsize=(8, 6)) X, Y = make_multilabel_classification(n_classes=2, n_labels=1, allow_unlabeled=True, random_state=1) plot_subfigure(X, Y, 1, "With unlabeled samples + CCA", "cca") plot_subfigure(X, Y, 2, "With unlabeled samples + PCA", "pca") X, Y = make_multilabel_classification(n_classes=2, n_labels=1, allow_unlabeled=False, random_state=1) plot_subfigure(X, Y, 3, "Without unlabeled samples + CCA", "cca") plot_subfigure(X, Y, 4, "Without unlabeled samples + PCA", "pca") plt.subplots_adjust(.04, .02, .97, .94, .09, .2) plt.show()
示例二:RBF内核的显式特征映射近似print(__doc__) # Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org> # Andreas Mueller <amueller@ais.uni-bonn.de> # License: BSD 3 clause # Standard scientific Python imports import matplotlib.pyplot as plt import numpy as np from time import time # Import datasets, classifiers and performance metrics from sklearn import datasets, svm, pipeline from sklearn.kernel_approximation import (RBFSampler, Nystroem) from sklearn.decomposition import PCA # The digits dataset digits = datasets.load_digits(n_class=9) # To apply an classifier on this data, we need to flatten the image, to # turn the data in a (samples, feature) matrix: n_samples = len(digits.data) data = digits.data / 16. data -= data.mean(axis=0) # We learn the digits on the first half of the digits data_train, targets_train = (data[:n_samples // 2], digits.target[:n_samples // 2]) # Now predict the value of the digit on the second half: data_test, targets_test = (data[n_samples // 2:], digits.target[n_samples // 2:]) # data_test = scaler.transform(data_test) # Create a classifier: a support vector classifier kernel_svm = svm.SVC(gamma=.2) linear_svm = svm.LinearSVC() # create pipeline from kernel approximation # and linear svm feature_map_fourier = RBFSampler(gamma=.2, random_state=1) feature_map_nystroem = Nystroem(gamma=.2, random_state=1) fourier_approx_svm = pipeline.Pipeline([("feature_map", feature_map_fourier), ("svm", svm.LinearSVC())]) nystroem_approx_svm = pipeline.Pipeline([("feature_map", feature_map_nystroem), ("svm", svm.LinearSVC())]) # fit and predict using linear and kernel svm: kernel_svm_time = time() kernel_svm.fit(data_train, targets_train) kernel_svm_score = kernel_svm.score(data_test, targets_test) kernel_svm_time = time() - kernel_svm_time linear_svm_time = time() linear_svm.fit(data_train, targets_train) linear_svm_score = linear_svm.score(data_test, targets_test) linear_svm_time = time() - linear_svm_time sample_sizes = 30 * np.arange(1, 10) fourier_scores = [] nystroem_scores = [] fourier_times = [] nystroem_times = [] for D in sample_sizes: fourier_approx_svm.set_params(feature_map__n_components=D) nystroem_approx_svm.set_params(feature_map__n_components=D) start = time() nystroem_approx_svm.fit(data_train, targets_train) nystroem_times.append(time() - start) start = time() fourier_approx_svm.fit(data_train, targets_train) fourier_times.append(time() - start) fourier_score = fourier_approx_svm.score(data_test, targets_test) nystroem_score = nystroem_approx_svm.score(data_test, targets_test) nystroem_scores.append(nystroem_score) fourier_scores.append(fourier_score) # plot the results: plt.figure(figsize=(8, 8)) accuracy = plt.subplot(211) # second y axis for timeings timescale = plt.subplot(212) accuracy.plot(sample_sizes, nystroem_scores, label="Nystroem approx. kernel") timescale.plot(sample_sizes, nystroem_times, '--', label='Nystroem approx. kernel') accuracy.plot(sample_sizes, fourier_scores, label="Fourier approx. kernel") timescale.plot(sample_sizes, fourier_times, '--', label='Fourier approx. kernel') # horizontal lines for exact rbf and linear kernels: accuracy.plot([sample_sizes[0], sample_sizes[-1]], [linear_svm_score, linear_svm_score], label="linear svm") timescale.plot([sample_sizes[0], sample_sizes[-1]], [linear_svm_time, linear_svm_time], '--', label='linear svm') accuracy.plot([sample_sizes[0], sample_sizes[-1]], [kernel_svm_score, kernel_svm_score], label="rbf svm") timescale.plot([sample_sizes[0], sample_sizes[-1]], [kernel_svm_time, kernel_svm_time], '--', label='rbf svm') # vertical line for dataset dimensionality = 64 accuracy.plot([64, 64], [0.7, 1], label="n_features") # legends and labels accuracy.set_title("Classification accuracy") timescale.set_title("Training times") accuracy.set_xlim(sample_sizes[0], sample_sizes[-1]) accuracy.set_xticks(()) accuracy.set_ylim(np.min(fourier_scores), 1) timescale.set_xlabel("Sampling steps = transformed feature dimension") accuracy.set_ylabel("Classification accuracy") timescale.set_ylabel("Training time in seconds") accuracy.legend(loc='best') timescale.legend(loc='best') # visualize the decision surface, projected down to the first # two principal components of the dataset pca = PCA(n_components=8).fit(data_train) X = pca.transform(data_train) # Generate grid along first two principal components multiples = np.arange(-2, 2, 0.1) # steps along first component first = multiples[:, np.newaxis] * pca.components_[0, :] # steps along second component second = multiples[:, np.newaxis] * pca.components_[1, :] # combine grid = first[np.newaxis, :, :] + second[:, np.newaxis, :] flat_grid = grid.reshape(-1, data.shape[1]) # title for the plots titles = ['SVC with rbf kernel', 'SVC (linear kernel)\n with Fourier rbf feature map\n' 'n_components=100', 'SVC (linear kernel)\n with Nystroem rbf feature map\n' 'n_components=100'] plt.tight_layout() plt.figure(figsize=(12, 5)) # predict and plot for i, clf in enumerate((kernel_svm, nystroem_approx_svm, fourier_approx_svm)): # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, x_max]x[y_min, y_max]. plt.subplot(1, 3, i + 1) Z = clf.predict(flat_grid) # Put the result into a color plot Z = Z.reshape(grid.shape[:-1]) plt.contourf(multiples, multiples, Z, cmap=plt.cm.Paired) plt.axis('off') # Plot also the training points plt.scatter(X[:, 0], X[:, 1], c=targets_train, cmap=plt.cm.Paired, edgecolors=(0, 0, 0)) plt.title(titles[i]) plt.tight_layout() plt.show()
-
Python -机器学习 -svm.SVC分类
2020-06-24 13:28:38svm.SVC参数 文档 sklearn.svm.SVC(C=1.0, kernel='rbf', degree=3, gamma='auto', coef0=0.0, shrinking=True, probability=False, tol=0.001, cache_size=200, class_weight=None, verbose=False, max_iter=-1, ... -
sklearn.svm.SVC()函数解析(最清晰的解释)
2019-08-15 19:17:13sklearn.svm.SVC()函数全称为C-支持向量分类器。 class sklearn.svm.SVC(C=1.0, kernel=’rbf’, degree=3, gamma=’auto_deprecated’, coef0=0.0, shrinking=True, probability=False, tol=0.001, ... -
为什么预测概率函数sklearn.svm.svc给出概率是否大于1?
2020-12-20 05:34:10我有一个sklearn.svm.svc(RBF核)模型训练在两个类上,每个类包含140个样本。当我试图预测时,概率设置为true,这两个类的预测概率是不同的。在对于某些测试样本,它给出的概率大于1其他不到一个例如:“样品1”:1.... -
sklearn.svm.SVC详解
2020-09-23 18:25:15sklearn.svm.SVC详解 -
sklearn.svm.LinearSVC与sklearn.svm.SVC区别
2020-04-02 22:05:061.LinearSVC与SVC的区别 LinearSVC 基于liblinear库实现 有多种惩罚参数和损失函数可供选择 训练集实例数量大(大于1万)时也可以很好地进行归一化 既支持稠密输入矩阵也支持稀疏输入矩阵 多分类问题采用one-vs-... -
python sklearn.svm.SVC支持向量机实例
2019-10-22 14:17:54分类 import numpy as np import matplotlib.pyplot as plt from sklearn import svm,datasets def make_meshgrid(x,y,h=.02): x_min,x_max=x.min()-1,x.max()+1 y_min,y_max=y.min()-1,y.max()+1 xx,yy=... -
sklearn.svm.SVC中kernel参数说明
2020-08-07 11:04:02sklearn.svm.SVC中kernel参数说明 常用核函数 线性核函数kernel='linear' 多项式核函数kernel='poly' 径向基核函数kernel='rbf' sigmod核函数kernel='sigmod' 常用核函数 线性核函数kernel=‘linear’... -
python机器学习之sklearn.svm.SVC详解
2020-06-21 11:11:09sklearn.svm.SVC(C=1.0, kernel=‘rbf’, degree=3, gamma=‘auto’, coef0=0.0, shrinking=True, probability=False, tol=0.001, cache_size=200, class_weight=None, verbose=False, max_iter=-1, decision_... -
支持向量机SVM--sklearn.svm.SVC【机器学习笔记简摘】
2021-10-29 00:35:51SVM 是一个非常优雅的算法,具有完善的数学理论,常用于数据分类,也可以用于数据的回归预测中,由于其优美的理论保证和利用核函数对于线性不可分问题的处理技巧, 在上世纪90年代左右,SVM 曾红极一时。 SVM囊括很... -
sklearn.svm.SVC() 参数说明
2020-06-22 15:53:29sklearn.svm.SVC(C=1.0, kernel=‘rbf’, degree=3, gamma=‘auto’, coef0=0.0, shrinking=True, probability=False,tol=0.001, cache_size=200, class_weight=None, verbose=False, max_iter=-1, decision_... -
sklearn.svm.SVC 参数说明
2019-10-15 10:50:28sklearn中的SVC函数 本身这个函数也是基于libsvm实现的,所以在参数设置上有很多相似的地方...sklearn.svm.SVC(C=1.0,kernel='rbf',degree=3,gamma='auto',coef0=0.0,shrinking=True,probability=False,tol=0.001... -
python|支持向量机(svm.SVC)
2019-11-05 16:32:28# -*- coding: utf-8 -*- """ Created on Tue Nov 5 16:30:52 2019 ...from sklearn.svm import SVC import pandas as pd import numpy as np import sklearn.datasets as skdata import matpl... -
支持向量机SVM原理以及sklearn的实现(以及sklearn.svm.SVC参数说明)
2019-07-18 18:02:47一)支持向量机历史 1995年Cortes和Vapnik于首先提出了支持向量机(Support...SVM是一种有监督的机器学习算法,解决的是二元分类问题,即分两类的问题,多元分类问题可以通过构造多个SVM分类器的方法来解决。 SVM有两... -
【机器学习】svm.SVC参数详解
2019-06-20 21:48:17sklearn.svm.SVC(C=1.0, kernel='rbf', degree=3, gamma='auto', coef0=0.0, shrinking=True, probability=False, tol=0.001, cache_size=200, class_weight=None, verbose=False, max_iter=-1, decision_function_s... -
sklearn.svm.SVC的参数学习笔记
2019-03-12 11:57:55sklearn.svm.SVC的常用核函数kernel说明常用kernel线性核函数kernel='linear'多项式核函数kernel=‘poly’径向基函数kernel=‘rbf’Sigmod核函数kernel='sigmod’ 常用kernel 线性核函数kernel=‘linear’ 这与使用... -
svm.SVC API说明
2019-05-20 16:04:26svm.SVC API说明: 功能:使用SVM分类器进行模型构建 # 参数说明: # C: 误差项的惩罚系数,默认为1.0;一般为大于0的一个数字,C越大表示在训练过程中对于总误差的关注度越高,也就是说当C越大的时候,对于训练集的... -
sklearn.svm.SVC中decision_function_shape问题
2020-04-16 17:20:18svm支持向量机设计二分类问题,当遇到多分类问题时需要构造多类分类器,主要有两种方法:一种是直接法,直接在目标函数上进行修改,一般计算相对复杂;另一类是间接法,通过组合多个二分类器来实现,常见方法有one-... -
SVM.SVC,支持向量机的笔记
2019-06-21 10:00:07from sklearn import svm form sklearn.model_selection import GridSearchCV #新版本的...svm.SVC(C = 1.0,kernel =‘rbf’,degree = 3,gamma =‘auto_deprecated’,coef0 = 0.0,shrinking = True,probabi... -
python sklearn.svm.SVC() 使用方法
2019-08-02 15:40:46引用 -
sklearn.svm.SVC()
2021-12-04 16:23:41sklearn中的SVC函数是基于libsvm实现的,所以在参数设置上有很多相似的地方。(PS: libsvm中的二次规划问题的解决算法是SMO)。 对于SVC函数的参数解释如下:(主要翻译的sklearn 文档) 参数 C: float参数 ... -
Sklearn学习笔记---支持向量机SVM中svm.svc使用
2018-10-08 17:20:52SVM及Sklearn使用 支持向量机SVM 支持向量机SVM,是常见的一种判别方法, 在机器学习领域是有监督学习模型,通常用来进行模式识别、分类及回归。 主要思想: 对线性可分情况进行判别;对线性不可分的情况,通过... -
SVM.SVC调参实战总结与指南
2019-11-18 16:33:23SVC(C=1.0,kernel=’rbf’,degree=3,gamma=’auto_deprecated’,coef0=0.0,shrinking=True,probability=False,tol=0.001,cache_size=200,class_weight=None,verbose=False,max_iter=-1,decision_func... -
sklearn.svm.SVC 调参说明
2018-12-19 15:20:19经常用到sklearn中的SVC函数,这里把文档中的参数翻译了一些,以备不时之需。 本身这个函数也是基于libsvm...sklearn.svm.SVC(C=1.0, kernel='rbf', degree=3, gamma='auto', coef0=0.0, shrinking=True, ...