1.4.Support Vector Machines#

Support vector machines (SVMs) are a set of supervised learningmethods used forclassification,regression andoutliers detection.

The advantages of support vector machines are:

  • Effective in high dimensional spaces.

  • Still effective in cases where number of dimensions is greaterthan the number of samples.

  • Uses a subset of training points in the decision function (calledsupport vectors), so it is also memory efficient.

  • Versatile: differentKernel functions can bespecified for the decision function. Common kernels areprovided, but it is also possible to specify custom kernels.

The disadvantages of support vector machines include:

  • If the number of features is much greater than the number ofsamples, avoid over-fitting in choosingKernel functions and regularizationterm is crucial.

  • SVMs do not directly provide probability estimates, these arecalculated using an expensive five-fold cross-validation(seeScores and probabilities, below).

The support vector machines in scikit-learn support both dense(numpy.ndarray and convertible to that bynumpy.asarray) andsparse (anyscipy.sparse) sample vectors as input. However, to usean SVM to make predictions for sparse data, it must have been fit on suchdata. For optimal performance, use C-orderednumpy.ndarray (dense) orscipy.sparse.csr_matrix (sparse) withdtype=float64.

1.4.1.Classification#

SVC,NuSVC andLinearSVC are classescapable of performing binary and multi-class classification on a dataset.

../_images/sphx_glr_plot_iris_svc_001.png

SVC andNuSVC are similar methods, but accept slightlydifferent sets of parameters and have different mathematical formulations (seesectionMathematical formulation). On the other hand,LinearSVC is another (faster) implementation of Support VectorClassification for the case of a linear kernel. It alsolacks some of the attributes ofSVC andNuSVC, likesupport_.LinearSVC usessquared_hinge loss and due to itsimplementation inliblinear it also regularizes the intercept, if considered.This effect can however be reduced by carefully fine tuning itsintercept_scaling parameter, which allows the intercept term to have adifferent regularization behavior compared to the other features. Theclassification results and score can therefore differ from the other twoclassifiers.

As other classifiers,SVC,NuSVC andLinearSVC take as input two arrays: an arrayX of shape(n_samples,n_features) holding the training samples, and an arrayy ofclass labels (strings or integers), of shape(n_samples):

>>>fromsklearnimportsvm>>>X=[[0,0],[1,1]]>>>y=[0,1]>>>clf=svm.SVC()>>>clf.fit(X,y)SVC()

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

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

SVMs decision function (detailed in theMathematical formulation)depends on some subset of the training data, called the support vectors. Someproperties of these support vectors can be found in attributessupport_vectors_,support_ andn_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]...)

Examples

1.4.1.1.Multi-class classification#

SVC andNuSVC implement the “one-versus-one” (“ovo”)approach for multi-class classification, which constructsn_classes*(n_classes-1)/2classifiers, each trained on data from two classes. Internally, the solveralways uses this “ovo” strategy to train the models. However, by default, thedecision_function_shape parameter is set to"ovr" (“one-vs-rest”), to havea consistent interface with other classifiers by monotonically transforming the “ovo”decision function into an “ovr” decision function of shape(n_samples,n_classes).

>>>X=[[0],[1],[2],[3]]>>>Y=[0,1,2,3]>>>clf=svm.SVC(decision_function_shape='ovo')>>>clf.fit(X,Y)SVC(decision_function_shape='ovo')>>>dec=clf.decision_function([[1]])>>>dec.shape[1]# 6 classes: 4*3/2 = 66>>>clf.decision_function_shape="ovr">>>dec=clf.decision_function([[1]])>>>dec.shape[1]# 4 classes4

On the other hand,LinearSVC implements a “one-vs-rest” (“ovr”)multi-class strategy, thus trainingn_classes models.

>>>lin_clf=svm.LinearSVC()>>>lin_clf.fit(X,Y)LinearSVC()>>>dec=lin_clf.decision_function([[1]])>>>dec.shape[1]4

SeeMathematical formulation for a complete description ofthe decision function.

Details on multi-class strategies#

Note that theLinearSVC also implements an alternative multi-classstrategy, the so-called multi-class SVM formulated by Crammer and Singer[16], by using the optionmulti_class='crammer_singer'. In practice,one-vs-rest classification is usually preferred, since the results are mostlysimilar, but the runtime is significantly less.

For “one-vs-rest”LinearSVC the attributescoef_ andintercept_have the shape(n_classes,n_features) and(n_classes,) respectively.Each row of the coefficients corresponds to one of then_classes“one-vs-rest” classifiers and similar for the intercepts, in theorder of the “one” class.

In the case of “one-vs-one”SVC andNuSVC, the layout ofthe attributes is a little more involved. In the case of a linearkernel, the attributescoef_ andintercept_ have the shape(n_classes*(n_classes-1)/2,n_features) and(n_classes*(n_classes-1)/2) respectively. This is similar to the layout forLinearSVC described above, with each row now correspondingto a binary classifier. The order for classes0 to n is “0 vs 1”, “0 vs 2” , … “0 vs n”, “1 vs 2”, “1 vs 3”, “1 vs n”, . .. “n-1 vs n”.

The shape ofdual_coef_ is(n_classes-1,n_SV) witha somewhat hard to grasp layout.The columns correspond to the support vectors involved in anyof then_classes*(n_classes-1)/2 “one-vs-one” classifiers.Each support vectorv has a dual coefficient in each of then_classes-1 classifiers comparing the class ofv against another class.Note that some, but not all, of these dual coefficients, may be zero.Then_classes-1 entries in each column are these dual coefficients,ordered by the opposing class.

This might be clearer with an example: consider a three class problem withclass 0 having three support vectors\(v^{0}_0, v^{1}_0, v^{2}_0\) and class 1 and 2 having two support vectors\(v^{0}_1, v^{1}_1\) and\(v^{0}_2, v^{1}_2\) respectively. For eachsupport vector\(v^{j}_i\), there are two dual coefficients. Let’s callthe coefficient of support vector\(v^{j}_i\) in the classifier betweenclasses\(i\) and\(k\)\(\alpha^{j}_{i,k}\).Thendual_coef_ looks like this:

\(\alpha^{0}_{0,1}\)

\(\alpha^{1}_{0,1}\)

\(\alpha^{2}_{0,1}\)

\(\alpha^{0}_{1,0}\)

\(\alpha^{1}_{1,0}\)

\(\alpha^{0}_{2,0}\)

\(\alpha^{1}_{2,0}\)

\(\alpha^{0}_{0,2}\)

\(\alpha^{1}_{0,2}\)

\(\alpha^{2}_{0,2}\)

\(\alpha^{0}_{1,2}\)

\(\alpha^{1}_{1,2}\)

\(\alpha^{0}_{2,1}\)

\(\alpha^{1}_{2,1}\)

Coefficientsfor SVs of class 0

Coefficientsfor SVs of class 1

Coefficientsfor SVs of class 2

Examples

1.4.1.2.Scores and probabilities#

Thedecision_function method ofSVC andNuSVC givesper-class scores for each sample (or a single score per sample in the binarycase). When the constructor optionprobability is set toTrue,class membership probability estimates (from the methodspredict_proba andpredict_log_proba) are enabled. In the binary case, the probabilities arecalibrated using Platt scaling[9]: logistic regression on the SVM’s scores,fit by an additional cross-validation on the training data.In the multiclass case, this is extended as per[10].

Note

The same probability calibration procedure is available for all estimatorsvia theCalibratedClassifierCV (seeProbability calibration). In the case ofSVC andNuSVC, thisprocedure is builtin tolibsvm which is used under the hood, so it doesnot rely on scikit-learn’sCalibratedClassifierCV.

The cross-validation involved in Platt scalingis an expensive operation for large datasets.In addition, the probability estimates may be inconsistent with the scores:

  • the “argmax” of the scores may not be the argmax of the probabilities

  • in binary classification, a sample may be labeled bypredict asbelonging to the positive class even if the output ofpredict_proba isless than 0.5; and similarly, it could be labeled as negative even if theoutput ofpredict_proba is more than 0.5.

Platt’s method is also known to have theoretical issues.If confidence scores are required, but these do not have to be probabilities,then it is advisable to setprobability=Falseand usedecision_function instead ofpredict_proba.

Please note that whendecision_function_shape='ovr' andn_classes>2,unlikedecision_function, thepredict method does not try to break tiesby default. You can setbreak_ties=True for the output ofpredict to bethe same asnp.argmax(clf.decision_function(...),axis=1), otherwise thefirst class among the tied classes will always be returned; but have in mindthat it comes with a computational cost. SeeSVM Tie Breaking Example for an example ontie breaking.

1.4.1.3.Unbalanced problems#

In problems where it is desired to give more importance to certainclasses or certain individual samples, the parametersclass_weight andsample_weight can be used.

SVC (but notNuSVC) implements the parameterclass_weight in thefit method. It’s a dictionary of the form{class_label:value}, where value is a floating point number > 0that sets the parameterC of classclass_label toC*value.The figure below illustrates the decision boundary of an unbalanced problem,with and without weight correction.

../_images/sphx_glr_plot_separating_hyperplane_unbalanced_001.png

SVC,NuSVC,SVR,NuSVR,LinearSVC,LinearSVR andOneClassSVM implement also weights forindividual samples in thefit method through thesample_weight parameter.Similar toclass_weight, this sets the parameterC for the i-thexample toC*sample_weight[i], which will encourage the classifier toget these samples right. The figure below illustrates the effect of sampleweighting on the decision boundary. The size of the circles is proportionalto the sample weights:

../_images/sphx_glr_plot_weighted_samples_001.png

Examples

1.4.2.Regression#

The method of Support Vector Classification can be extended to solveregression problems. This method is called Support Vector Regression.

The model produced by support vector classification (as describedabove) depends only on a subset of the training data, because the costfunction for building the model does not care about training pointsthat lie beyond the margin. Analogously, the model produced by SupportVector Regression depends only on a subset of the training data,because the cost function ignores samples whose prediction is close to theirtarget.

There are three different implementations of Support Vector Regression:SVR,NuSVR andLinearSVR.LinearSVRprovides a faster implementation thanSVR but only considers thelinear kernel, whileNuSVR implements a slightly different formulationthanSVR andLinearSVR. Due to its implementation inliblinearLinearSVR also regularizes the intercept, if considered.This effect can however be reduced by carefully fine tuning itsintercept_scaling parameter, which allows the intercept term to have adifferent regularization behavior compared to the other features. Theclassification results and score can therefore differ from the other twoclassifiers. SeeImplementation details for further details.

As with classification classes, the fit method will take asargument vectors X, y, only that in this case y is expected to havefloating point values instead of integer values:

>>>fromsklearnimportsvm>>>X=[[0,0],[2,2]]>>>y=[0.5,2.5]>>>regr=svm.SVR()>>>regr.fit(X,y)SVR()>>>regr.predict([[1,1]])array([1.5])

Examples

1.4.3.Density estimation, novelty detection#

The classOneClassSVM implements a One-Class SVM which is used inoutlier detection.

SeeNovelty and Outlier Detection for the description and usage of OneClassSVM.

1.4.4.Complexity#

Support Vector Machines are powerful tools, but their compute andstorage requirements increase rapidly with the number of trainingvectors. The core of an SVM is a quadratic programming problem (QP),separating support vectors from the rest of the training data. The QPsolver used by thelibsvm-based implementation scales between\(O(n_{features} \times n_{samples}^2)\) and\(O(n_{features} \times n_{samples}^3)\) depending on how efficientlythelibsvm cache is used in practice (dataset dependent). If the datais very sparse\(n_{features}\) should be replaced by the average numberof non-zero features in a sample vector.

For the linear case, the algorithm used inLinearSVC by theliblinear implementation is much moreefficient than itslibsvm-basedSVC counterpart and canscale almost linearly to millions of samples and/or features.

1.4.5.Tips on Practical Use#

  • Avoiding data copy: ForSVC,SVR,NuSVC andNuSVR, if the data passed to certain methods is not C-orderedcontiguous and double precision, it will be copied before calling theunderlying C implementation. You can check whether a given numpy array isC-contiguous by inspecting itsflags attribute.

    ForLinearSVC (andLogisticRegression) any input passed as a numpyarray will be copied and converted to theliblinear internal sparse datarepresentation (double precision floats and int32 indices of non-zerocomponents). If you want to fit a large-scale linear classifier withoutcopying a dense numpy C-contiguous double precision array as input, wesuggest to use theSGDClassifier class instead. The objectivefunction can be configured to be almost the same as theLinearSVCmodel.

  • Kernel cache size: ForSVC,SVR,NuSVC andNuSVR, the size of the kernel cache has a strong impact on runtimes for larger problems. If you have enough RAM available, it isrecommended to setcache_size to a higher value than the default of200(MB), such as 500(MB) or 1000(MB).

  • Setting C:C is1 by default and it’s a reasonable defaultchoice. If you have a lot of noisy observations you should decrease it:decreasing C corresponds to more regularization.

    LinearSVC andLinearSVR are less sensitive toC whenit becomes large, and prediction results stop improving after a certainthreshold. Meanwhile, largerC values will take more time to train,sometimes up to 10 times longer, as shown in[11].

  • Support Vector Machine algorithms are not scale invariant, soitis highly recommended to scale your data. For example, scale eachattribute on the input vector X to [0,1] or [-1,+1], or standardize itto have mean 0 and variance 1. Note that thesame scaling must beapplied to the test vector to obtain meaningful results. This can be doneeasily by using aPipeline:

    >>>fromsklearn.pipelineimportmake_pipeline>>>fromsklearn.preprocessingimportStandardScaler>>>fromsklearn.svmimportSVC>>>clf=make_pipeline(StandardScaler(),SVC())

    See sectionPreprocessing data for more details on scaling andnormalization.

  • Regarding theshrinking parameter, quoting[12]:We found that if thenumber of iterations is large, then shrinking can shorten the trainingtime. However, if we loosely solve the optimization problem (e.g., byusing a large stopping tolerance), the code without using shrinking maybe much faster

  • Parameternu inNuSVC/OneClassSVM/NuSVRapproximates the fraction of training errors and support vectors.

  • InSVC, if the data is unbalanced (e.g. manypositive and few negative), setclass_weight='balanced' and/or trydifferent penalty parametersC.

  • Randomness of the underlying implementations: The underlyingimplementations ofSVC andNuSVC use a random numbergenerator only to shuffle the data for probability estimation (whenprobability is set toTrue). This randomness can be controlledwith therandom_state parameter. Ifprobability is set toFalsethese estimators are not random andrandom_state has no effect on theresults. The underlyingOneClassSVM implementation is similar tothe ones ofSVC andNuSVC. As no probability estimationis provided forOneClassSVM, it is not random.

    The underlyingLinearSVC implementation uses a random numbergenerator to select features when fitting the model with a dual coordinatedescent (i.e. whendual is set toTrue). It is thus not uncommonto have slightly different results for the same input data. If thathappens, try with a smallertol parameter. This randomness can also becontrolled with therandom_state parameter. Whendual isset toFalse the underlying implementation ofLinearSVC isnot random andrandom_state has no effect on the results.

  • Using L1 penalization as provided byLinearSVC(penalty='l1',dual=False) yields a sparse solution, i.e. only a subset of featureweights is different from zero and contribute to the decision function.IncreasingC yields a more complex model (more features are selected).TheC value that yields a “null” model (all weights equal to zero) canbe calculated usingl1_min_c.

1.4.6.Kernel functions#

Thekernel function can be any of the following:

  • linear:\(\langle x, x'\rangle\).

  • polynomial:\((\gamma \langle x, x'\rangle + r)^d\), where\(d\) is specified by parameterdegree,\(r\) bycoef0.

  • rbf:\(\exp(-\gamma \|x-x'\|^2)\), where\(\gamma\) isspecified by parametergamma, must be greater than 0.

  • sigmoid\(\tanh(\gamma \langle x,x'\rangle + r)\),where\(r\) is specified bycoef0.

Different kernels are specified by thekernel parameter:

>>>linear_svc=svm.SVC(kernel='linear')>>>linear_svc.kernel'linear'>>>rbf_svc=svm.SVC(kernel='rbf')>>>rbf_svc.kernel'rbf'

See alsoKernel Approximation for a solution to use RBF kernels that is much faster and more scalable.

1.4.6.1.Parameters of the RBF Kernel#

When training an SVM with theRadial Basis Function (RBF) kernel, twoparameters must be considered:C andgamma. The parameterC,common to all SVM kernels, trades off misclassification of training examplesagainst simplicity of the decision surface. A lowC makes the decisionsurface smooth, while a highC aims at classifying all training examplescorrectly.gamma defines how much influence a single training example has.The largergamma is, the closer other examples must be to be affected.

Proper choice ofC andgamma is critical to the SVM’s performance. Oneis advised to useGridSearchCV withC andgamma spaced exponentially far apart to choose good values.

Examples

1.4.6.2.Custom Kernels#

You can define your own kernels by either giving the kernel as apython function or by precomputing the Gram matrix.

Classifiers with custom kernels behave the same way as any otherclassifiers, except that:

  • Fieldsupport_vectors_ is now empty, only indices of supportvectors are stored insupport_

  • A reference (and not a copy) of the first argument in thefit()method is stored for future reference. If that array changes between theuse offit() andpredict() you will have unexpected results.

Using Python functions as kernels#

You can use your own defined kernels by passing a function to thekernel parameter.

Your kernel must take as arguments two matrices of shape(n_samples_1,n_features),(n_samples_2,n_features)and return a kernel matrix of shape(n_samples_1,n_samples_2).

The following code defines a linear kernel and creates a classifierinstance that will use that kernel:

>>>importnumpyasnp>>>fromsklearnimportsvm>>>defmy_kernel(X,Y):...returnnp.dot(X,Y.T)...>>>clf=svm.SVC(kernel=my_kernel)
Using the Gram matrix#

You can pass pre-computed kernels by using thekernel='precomputed'option. You should then pass Gram matrix instead of X to thefit andpredict methods. The kernel values betweenall training vectors and thetest vectors must be provided:

>>>importnumpyasnp>>>fromsklearn.datasetsimportmake_classification>>>fromsklearn.model_selectionimporttrain_test_split>>>fromsklearnimportsvm>>>X,y=make_classification(n_samples=10,random_state=0)>>>X_train,X_test,y_train,y_test=train_test_split(X,y,random_state=0)>>>clf=svm.SVC(kernel='precomputed')>>># linear kernel computation>>>gram_train=np.dot(X_train,X_train.T)>>>clf.fit(gram_train,y_train)SVC(kernel='precomputed')>>># predict on training examples>>>gram_test=np.dot(X_test,X_train.T)>>>clf.predict(gram_test)array([0, 1, 0])

Examples

1.4.7.Mathematical formulation#

A support vector machine constructs a hyper-plane or set of hyper-planes in ahigh or infinite dimensional space, which can be used forclassification, regression or other tasks. Intuitively, a goodseparation is achieved by the hyper-plane that has the largest distanceto the nearest training data points of any class (so-called functionalmargin), since in general the larger the margin the lower thegeneralization error of the classifier. The figure below shows the decisionfunction for a linearly separable problem, with three samples on themargin boundaries, called “support vectors”:

../_images/sphx_glr_plot_separating_hyperplane_001.png

In general, when the problem isn’t linearly separable, the support vectorsare the sampleswithin the margin boundaries.

We recommend[13] and[14] as good references for the theory andpracticalities of SVMs.

1.4.7.1.SVC#

Given training vectors\(x_i \in \mathbb{R}^p\), i=1,…, n, in two classes, and avector\(y \in \{1, -1\}^n\), our goal is to find\(w \in\mathbb{R}^p\) and\(b \in \mathbb{R}\) such that the prediction given by\(\text{sign} (w^T\phi(x) + b)\) is correct for most samples.

SVC solves the following primal problem:

\[ \begin{align}\begin{aligned}\min_ {w, b, \zeta} \frac{1}{2} w^T w + C \sum_{i=1}^{n} \zeta_i\\\begin{split}\textrm {subject to } & y_i (w^T \phi (x_i) + b) \geq 1 - \zeta_i,\\& \zeta_i \geq 0, i=1, ..., n\end{split}\end{aligned}\end{align} \]

Intuitively, we’re trying to maximize the margin (by minimizing\(||w||^2 = w^Tw\)), while incurring a penalty when a sample ismisclassified or within the margin boundary. Ideally, the value\(y_i(w^T \phi (x_i) + b)\) would be\(\geq 1\) for all samples, whichindicates a perfect prediction. But problems are usually not always perfectlyseparable with a hyperplane, so we allow some samples to be at a distance\(\zeta_i\) fromtheir correct margin boundary. The penalty termC controls the strength ofthis penalty, and as a result, acts as an inverse regularization parameter(see note below).

The dual problem to the primal is

\[ \begin{align}\begin{aligned}\min_{\alpha} \frac{1}{2} \alpha^T Q \alpha - e^T \alpha\\\begin{split}\textrm {subject to } & y^T \alpha = 0\\& 0 \leq \alpha_i \leq C, i=1, ..., n\end{split}\end{aligned}\end{align} \]

where\(e\) is the vector of all ones,and\(Q\) is an\(n\) by\(n\) positive semidefinite matrix,\(Q_{ij} \equiv y_i y_j K(x_i, x_j)\), where\(K(x_i, x_j) = \phi (x_i)^T \phi (x_j)\)is the kernel. The terms\(\alpha_i\) are called the dual coefficients,and they are upper-bounded by\(C\).This dual representation highlights the fact that training vectors areimplicitly mapped into a higher (maybe infinite)dimensional space by the function\(\phi\): seekernel trick.

Once the optimization problem is solved, the output ofdecision_function for a given sample\(x\) becomes:

\[\sum_{i\in SV} y_i \alpha_i K(x_i, x) + b,\]

and the predicted class corresponds to its sign. We only need to sum over thesupport vectors (i.e. the samples that lie within the margin) because thedual coefficients\(\alpha_i\) are zero for the other samples.

These parameters can be accessed through the attributesdual_coef_which holds the product\(y_i \alpha_i\),support_vectors_ whichholds the support vectors, andintercept_ which holds the independentterm\(b\).

Note

While SVM models derived fromlibsvm andliblinear useC asregularization parameter, most other estimators usealpha. The exactequivalence between the amount of regularization of two models depends onthe exact objective function optimized by the model. For example, when theestimator used isRidge regression,the relation between them is given as\(C = \frac{1}{\alpha}\).

LinearSVC#

The primal problem can be equivalently formulated as

\[\min_ {w, b} \frac{1}{2} w^T w + C \sum_{i=1}^{n}\max(0, 1 - y_i (w^T \phi(x_i) + b)),\]

where we make use of thehinge loss. This is the form that isdirectly optimized byLinearSVC, but unlike the dual form, this onedoes not involve inner products between samples, so the famous kernel trickcannot be applied. This is why only the linear kernel is supported byLinearSVC (\(\phi\) is the identity function).

NuSVC#

The\(\nu\)-SVC formulation[15] is a reparameterization of the\(C\)-SVC and therefore mathematically equivalent.

We introduce a new parameter\(\nu\) (instead of\(C\)) whichcontrols the number of support vectors andmargin errors:\(\nu \in (0, 1]\) is an upper bound on the fraction of margin errors anda lower bound of the fraction of support vectors. A margin error correspondsto a sample that lies on the wrong side of its margin boundary: it is eithermisclassified, or it is correctly classified but does not lie beyond themargin.

1.4.7.2.SVR#

Given training vectors\(x_i \in \mathbb{R}^p\), i=1,…, n, and avector\(y \in \mathbb{R}^n\)\(\varepsilon\)-SVR solves the following primal problem:

\[ \begin{align}\begin{aligned}\min_ {w, b, \zeta, \zeta^*} \frac{1}{2} w^T w + C \sum_{i=1}^{n} (\zeta_i + \zeta_i^*)\\\begin{split}\textrm {subject to } & y_i - w^T \phi (x_i) - b \leq \varepsilon + \zeta_i,\\ & w^T \phi (x_i) + b - y_i \leq \varepsilon + \zeta_i^*,\\ & \zeta_i, \zeta_i^* \geq 0, i=1, ..., n\end{split}\end{aligned}\end{align} \]

Here, we are penalizing samples whose prediction is at least\(\varepsilon\)away from their true target. These samples penalize the objective by\(\zeta_i\) or\(\zeta_i^*\), depending on whether their predictionslie above or below the\(\varepsilon\) tube.

The dual problem is

\[ \begin{align}\begin{aligned}\min_{\alpha, \alpha^*} \frac{1}{2} (\alpha - \alpha^*)^T Q (\alpha - \alpha^*) + \varepsilon e^T (\alpha + \alpha^*) - y^T (\alpha - \alpha^*)\\\begin{split}\textrm {subject to } & e^T (\alpha - \alpha^*) = 0\\& 0 \leq \alpha_i, \alpha_i^* \leq C, i=1, ..., n\end{split}\end{aligned}\end{align} \]

where\(e\) is the vector of all ones,\(Q\) is an\(n\) by\(n\) positive semidefinite matrix,\(Q_{ij} \equiv K(x_i, x_j) = \phi (x_i)^T \phi (x_j)\)is the kernel. Here training vectors are implicitly mapped into a higher(maybe infinite) dimensional space by the function\(\phi\).

The prediction is:

\[\sum_{i \in SV}(\alpha_i - \alpha_i^*) K(x_i, x) + b\]

These parameters can be accessed through the attributesdual_coef_which holds the difference\(\alpha_i - \alpha_i^*\),support_vectors_ whichholds the support vectors, andintercept_ which holds the independentterm\(b\)

LinearSVR#

The primal problem can be equivalently formulated as

\[\min_ {w, b} \frac{1}{2} w^T w + C \sum_{i=1}^{n}\max(0, |y_i - (w^T \phi(x_i) + b)| - \varepsilon),\]

where we make use of the epsilon-insensitive loss, i.e. errors of less than\(\varepsilon\) are ignored. This is the form that is directly optimizedbyLinearSVR.

1.4.8.Implementation details#

Internally, we uselibsvm[12] andliblinear[11] to handle allcomputations. These libraries are wrapped using C and Cython.For a description of the implementation and details of the algorithmsused, please refer to their respective papers.

References

[9]

Platt“Probabilistic outputs for SVMs and comparisons toregularized likelihood methods”.

[10]

Wu, Lin and Weng,“Probability estimates for multi-classclassification by pairwise coupling”,JMLR 5:975-1005, 2004.

[11](1,2)

Fan, Rong-En, et al.,“LIBLINEAR: A library for large linear classification.”,Journal of machine learning research 9.Aug (2008): 1871-1874.

[12](1,2)

Chang and Lin,LIBSVM: A Library for Support Vector Machines.

[13]

Bishop,Pattern recognition and machine learning,chapter 7 Sparse Kernel Machines.

[14]

“A Tutorial on Support Vector Regression”Alex J. Smola, Bernhard Schölkopf - Statistics and Computing archiveVolume 14 Issue 3, August 2004, p. 199-222.

[15]

Schölkopf et. alNew Support Vector Algorithms,Neural Computation 12, 1207-1245 (2000).

[16]

Crammer and SingerOn the Algorithmic Implementation of MulticlassKernel-based Vector Machines, JMLR 2001.