scikit-learn(工程中用的相对较多的模型介绍):1.4. Support Vector Machines

参考:http://scikit-learn.org/stable/modules/svm.html

在实际项目中,我们真的很少用到那些简单的模型,比如LR、kNN、NB等,虽然经典,但在工程中确实不实用。

今天我们关注在工程中用的相对较多的SVM。

SVM功能不少:Support vector machines (SVMs) are a set of supervised learning methods used for classificationregression and outliers
detection
.

好处多多:高维空间的高效率;维度大于样本数的有效性;仅使用训练点的子集(称作支持向量),空间占用少;有不同的kernel functions供选择。

也有坏处:维度大于样本数的有效性----但维度如果相对样本数过高,则效果会非常差;不能直接提供概率估计,需要通过an expensive five-fold cross-validation (see Scores
and probabilities
, below).才能实现。

(SVM支持dense和sparse sample vectors,但是如果预测使用的sparse data,那训练也要使用稀疏数据。为了发挥SVM效用,请use
C-ordered numpy.ndarray (dense)
or scipy.sparse.csr_matrix (sparse)
with dtype=float64.)

1、分类

SVCNuSVC and LinearSVC 是三个可以进行multi-class分类的模型。三者的本质区别就是 have
different mathematical formulations,具体参考本文最后的公式。

SVCNuSVC and LinearSVC 和其他分类器一样,使用fit、predict方法:

>>> from sklearn import svm
>>> X = [[0, 0], [1, 1]]
>>> y = [0, 1]
>>> clf = svm.SVC()
>>> clf.fit(X, y)
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3,
gamma=0.0, kernel=‘rbf‘, max_iter=-1, probability=False, random_state=None,
shrinking=True, tol=0.001, verbose=False)

After being fitted, the model can then be used to predict new values:

>>>

>>> clf.predict([[2., 2.]])
array([1])

SVM中的支持向量的相关属性可以使用 support_vectors_support_ and n_support来获取:

>>> # get support vectors
>>> clf.support_vectors_
array([[ 0.,  0.],
       [ 1.,  1.]])
>>> # get indices of support vectors
>>> clf.support_
array([0, 1]...)
>>> # get number of support vectors for each class
>>> clf.n_support_
array([1, 1]...)

对于multi-class分类:

SVC and NuSVC 的机制是“one-against-one”(training n_class * (n_class - 1) / 2个 models),而 LinearSVC 的策略是“one-vs-the-rest”(training n_class个 models)
。而实践中,one-vs-rest是常用和较好的,因为结果其实差不多,但时间省好多。。。

[python] view
plain
copy

  1. >>> X = [[0], [1], [2], [3]]
  2. >>> Y = [0, 1, 2, 3]
  3. >>> clf = svm.SVC()
  4. >>> clf.fit(X, Y)
  5. SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3,
  6. gamma=0.0, kernel=‘rbf‘, max_iter=-1, probability=False, random_state=None,
  7. shrinking=True, tol=0.001, verbose=False)
  8. >>> dec = clf.decision_function([[1]])
  9. >>> dec.shape[1] # 4 classes: 4*3/2 = 6
  10. 6
  11. >>> lin_clf = svm.LinearSVC()
  12. >>> lin_clf.fit(X, Y)
  13. LinearSVC(C=1.0, class_weight=None, dual=True, fit_intercept=True,
  14. intercept_scaling=1, loss=‘squared_hinge‘, max_iter=1000,
  15. multi_class=‘ovr‘, penalty=‘l2‘, random_state=None, tol=0.0001,
  16. verbose=0)
  17. >>> dec = lin_clf.decision_function([[1]])
  18. >>> dec.shape[1]
  19. 4

关于样本所属类别的confidence:The SVC method decision_function gives
per-class scores for each sample。另外还有所谓的option probability,但是,If
confidence scores are required, but these do not have to be probabilities, then it is advisable to set probability=False and
use decision_function instead
of predict_proba.(主要是因为probability的理论背景有缺陷)

在每个class或者sample的权重不同的情况下,可以设置keywords class_weight andsample_weight :

类别权重:SVC (but
not NuSVC)
implement a keyword class_weight in
the fit method.
It’s a dictionary of the form {class_label : value}, where
value is a floating point number > 0 that sets the parameter C of
class class_label to C * value.

样本权重:SVCNuSVCSVRNuSVR and OneClassSVM implement
also weights for individual samples in method fit through
keyword sample_weight.
Similar to class_weight,
these set the parameter C for
the i-th example to C * sample_weight[i].

最后给几个例子:

2、回归

Support Vector Regression.

看能明白这句话不能:Analogously(to
SVClassfication), the model produced by Support Vector Regression depends only on a subset of the training data, because the cost function for building the model ignores any training data close to the model prediction.

同样也是三个模型: SVRNuSVR and LinearSVR

>>> from sklearn import svm
>>> X = [[0, 0], [2, 2]]
>>> y = [0.5, 2.5]
>>> clf = svm.SVR()
>>> clf.fit(X, y)
SVR(C=1.0, cache_size=200, coef0=0.0, degree=3, epsilon=0.1, gamma=0.0,
    kernel=‘rbf‘, max_iter=-1, shrinking=True, tol=0.001, verbose=False)
>>> clf.predict([[1, 1]])
array([ 1.5])

给个例子:

未完待续。。。

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-08-01 22:45:05

scikit-learn(工程中用的相对较多的模型介绍):1.4. Support Vector Machines的相关文章

scikit-learn(工程中用的相对较多的模型介绍):1.12. Multiclass and multilabel algorithms

http://scikit-learn.org/stable/modules/multiclass.html 在实际项目中,我们真的很少用到那些简单的模型,比如LR.kNN.NB等,虽然经典,但在工程中确实不实用. 今天我们关注在工程中用的相对较多的 Multiclass and multilabel algorithms. warning:scikit-learn的所有分类器都是可以do multiclass classification out-of-the-box(可直接使用),所以没必要

scikit-learn(工程中用的相对较多的模型介绍):1.13. Feature selection

参考:http://scikit-learn.org/stable/modules/feature_selection.html The classes in the sklearn.feature_selection module can be used for feature selection/dimensionality reduction on sample sets, either to improve estimators' accuracy scores or to boost

scikit-learn(工程中用的相对较多的模型介绍):1.14. Semi-Supervised

参考:http://scikit-learn.org/stable/modules/label_propagation.html The semi-supervised estimators insklearn.semi_supervised are able to make use of this additional unlabeled data to better capture the shape of the underlying data distribution and gener

Query意图分析:记一次完整的机器学习过程(scikit learn library学习笔记)

所谓学习问题,是指观察由n个样本组成的集合,并根据这些数据来预测未知数据的性质. 学习任务(一个二分类问题): 区分一个普通的互联网检索Query是否具有某个垂直领域的意图.假设现在有一个O2O领域的垂直搜索引擎,专门为用户提供团购.优惠券的检索:同时存在一个通用的搜索引擎,比如百度,通用搜索引擎希望能够识别出一个Query是否具有O2O检索意图,如果有则调用O2O垂直搜索引擎,获取结果作为通用搜索引擎的结果补充. 我们的目的是学习出一个分类器(classifier),分类器可以理解为一个函数,

Python之扩展包安装(scikit learn)

scikit learn 是Python下开源的机器学习包.(安装环境:win7.0 32bit和Python2.7) Python安装第三方扩展包较为方便的方法:easy_install + packages name 在官网 https://pypi.python.org/pypi/setuptools/#windows-simplified 下载名字为 的文件. 在命令行窗口运行 ,安装后,可在python2.7文件夹下生成Scripts文件夹.把路径D:\Python27\Scripts

scikit learn 模块 调参 pipeline+girdsearch 数据举例:文档分类

scikit learn 模块 调参 pipeline+girdsearch 数据举例:文档分类数据集 fetch_20newsgroups #-*- coding: UTF-8 -*- import numpy as np from sklearn.pipeline import Pipeline from sklearn.linear_model import SGDClassifier from sklearn.grid_search import GridSearchCV from sk

Linear Regression with Scikit Learn

Before you read ?This is a demo or practice about how to use Simple-Linear-Regression in scikit-learn with python. Following is the package version that I use below: The Python version: 3.6.2 The Numpy version: 1.8.0rc1 The Scikit-Learn version: 0.19

Scikit Learn安装教程

Windows下安装scikit-learn 准备工作 Python (>= 2.6 or >= 3.3), Numpy (>= 1.6.1) Scipy (>= 0.9), Matplotlib(可选). NumPy NumPy系统是Python的一种开源的数值计算扩展.这种工具可用来存储和处理大型矩阵,比Python自身的嵌套列表(nested list structure)结构要高效的多(该结构也可以用来表示矩阵(matrix)). Scipy SciPy是一款方便.易于使用

Scikit Learn

安装pip 代码如下:# wget "https://pypi.python.org/packages/source/p/pip/pip-1.5.4.tar.gz#md5=834b2904f92d46aaa333267fb1c922bb" --no-check-certificate# tar -xzvf pip-1.5.4.tar.gz# cd pip-1.5.4# python setup.py install 输入pip如果能看到信息证明安装成功. 安装scikit-learn