# Introduction
Support vector machines (SVMs) are a set of supervised learning methods used for classification, regression and outliers detection.

The advantages of support vector machines are:

* Effective in high dimensional spaces.
* Still effective in cases where number of dimensions is greater than the number of samples.
* Uses a subset of training points in the decision function (called support vectors), so it is also memory efficient.
* Versatile: different Kernel functions can be specified for the decision function. Common kernels are provided, 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 of samples, avoid over-fitting in choosing Kernel functions and regularization term is crucial.
* SVMs do not directly provide probability estimates, these are calculated using an expensive five-fold cross-validation (see Scores and probabilities, below).

The support vector machines in scikit-learn support both dense (numpy.ndarray and convertible to that by numpy.asarray) and sparse (any scipy.sparse) sample vectors as input. However, to use an SVM to make predictions for sparse data, it must have been fit on such data. For optimal performance, use C-ordered numpy.ndarray (dense) or scipy.sparse.csr_matrix (sparse) with dtype=float64.

### Definition scikit-learn
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)

# Mathematical Formulation


```python
from IPython.display import Image
Image(filename="svm_plot_separating_hyperplane_0011.png")
```

A support vector machine constructs a hyper-plane or set of hyper-planes in a high or infinite dimensional space, which can be used for classification, regression or other tasks. Intuitively, a good separation is achieved by the hyper-plane that has the largest distance to the nearest training data points of any class (so-called functional margin), since in general the larger the margin the lower the generalization error of the classifier


### Classification
Given vectors $x_i \in \mathbb{R}^p$ in tow classes and a vector $y \in \{1, -1\}^n$ SVC solves the 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}

its dual 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  is the vector of all ones, $C  \gt 0$ is the upper bound, 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. Here training vectors are implicitly mapped into a higher (maybe infinite) dimensional space by the function $\phi$.

The decision function is:

$\operatorname{sgn}(\sum_{i=1}^n y_i \alpha_i K(x_i, x) + \rho)$

### Regression

Given training vectors $x_i \in \mathbb{R}^p$, i=1,…, n, and a vector $y \in \mathbb{R}^n$ $\epsilon$-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}

Its dual 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, $C > 0$ is the upper bound, Q is an  by  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 decision function is:

$\sum_{i=1}^n (\alpha_i - \alpha_i^*) K(x_i, x) + \rho$

These parameters can be accessed through the members $dual_coef_$ which holds the difference , $support_vectors_$ which holds the support vectors, and $intercept_$ which holds the independent term $\rho$.





```python
Image(filename="precission-recall.png")
```


```python
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler, QuantileTransformer
from sklearn.metrics import classification_report, confusion_matrix
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
np.random.seed(100)

```


```python
def choose_scaler(xtrain, xtest, name='Standard'):
    scaler = None
    if name == 'Standard':
        scaler = StandardScaler()
    elif name == 'MinMax':
        scaler = MinMaxScaler()
    else:
        scaler = QuantileTransformer()
    
    xtrain = scaler.fit_transform(xtrain)
    xtest = scaler.transform(xtest)
    return xtrain, xtest
```


```python


data = load_breast_cancer()
print(data['feature_names'])
print('')
print('.' * 50)
x = data['data']
y = data['target']

xtrain, xtest, ytrain, ytest = train_test_split(x, y, shuffle=True)
print('shape of xtrain:', xtrain.shape)
print('shape of ')
    
xtrain, xtest = choose_scaler(xtrain, xtest, name='MinMax')
print('the scaled values are:')
print(xtrain)

clf = svm.SVC(gamma='scale')
clf.fit(xtrain, ytrain)

# step 3 make predictitions with test set
y_pred_train = clf.predict(xtrain)
y_pred = clf.predict(xtest)
    
# step 4 use confusion matrix and classification report
print('-' * 50)
print('Training set:')
print('Classification report:')
print(classification_report(ytrain, y_pred_train))
print('')
print('Confusion matrix:')
print(confusion_matrix(ytrain, y_pred_train))
print('-' * 50)



print('.' * 50)
print('Test set:')
print('Classification report:')
print(classification_report(ytest, y_pred))
print('')
print('Confusion matrix:')
print(confusion_matrix(ytest, y_pred))
print('.' * 50)
```

    ['mean radius' 'mean texture' 'mean perimeter' 'mean area'
     'mean smoothness' 'mean compactness' 'mean concavity'
     'mean concave points' 'mean symmetry' 'mean fractal dimension'
     'radius error' 'texture error' 'perimeter error' 'area error'
     'smoothness error' 'compactness error' 'concavity error'
     'concave points error' 'symmetry error' 'fractal dimension error'
     'worst radius' 'worst texture' 'worst perimeter' 'worst area'
     'worst smoothness' 'worst compactness' 'worst concavity'
     'worst concave points' 'worst symmetry' 'worst fractal dimension']
    
    ..................................................
    shape of xtrain: (426, 30)
    shape of 
    the scaled values are:
    [[0.39058824 0.66       0.40235294 ... 0.55529412 0.08705882 0.63294118]
     [0.55647059 0.48235294 0.56705882 ... 0.62352941 0.53176471 0.72470588]
     [0.10588235 0.28117647 0.10823529 ... 0.4        0.39882353 0.79529412]
     ...
     [0.24705882 0.32470588 0.22588235 ... 0.12235294 0.42352941 0.16      ]
     [0.42705882 0.40235294 0.44       ... 0.35176471 0.46823529 0.47176471]
     [0.04705882 0.08235294 0.04941176 ... 0.30823529 0.92235294 0.71764706]]
    --------------------------------------------------
    Training set:
    Classification report:
                  precision    recall  f1-score   support
    
               0       0.99      0.98      0.99       156
               1       0.99      1.00      0.99       270
    
        accuracy                           0.99       426
       macro avg       0.99      0.99      0.99       426
    weighted avg       0.99      0.99      0.99       426
    
    
    Confusion matrix:
    [[153   3]
     [  1 269]]
    --------------------------------------------------
    ..................................................
    Test set:
    Classification report:
                  precision    recall  f1-score   support
    
               0       0.98      0.95      0.96        56
               1       0.97      0.99      0.98        87
    
        accuracy                           0.97       143
       macro avg       0.97      0.97      0.97       143
    weighted avg       0.97      0.97      0.97       143
    
    
    Confusion matrix:
    [[53  3]
     [ 1 86]]
    ..................................................


    D:\anaconda\lib\site-packages\sklearn\preprocessing\data.py:2239: UserWarning: n_quantiles (1000) is greater than the total number of samples (426). n_quantiles is set to n_samples.
      % (self.n_quantiles, n_samples))


# Cross validation

When evaluating different settings (“hyperparameters”) for estimators, such as the C setting that must be manually set for an SVM, there is still a risk of overfitting on the test set because the parameters can be tweaked until the estimator performs optimally. This way, knowledge about the test set can “leak” into the model and evaluation metrics no longer report on generalization performance. To solve this problem, yet another part of the dataset can be held out as a so-called “validation set”: training proceeds on the training set, after which evaluation is done on the validation set, and when the experiment seems to be successful, final evaluation can be done on the test set.

However, by partitioning the available data into three sets, we drastically reduce the number of samples which can be used for learning the model, and the results can depend on a particular random choice for the pair of (train, validation) sets.

A solution to this problem is a procedure called cross-validation (CV for short). A test set should still be held out for final evaluation, but the validation set is no longer needed when doing CV. In the basic approach, called k-fold CV, the training set is split into k smaller sets (other approaches are described below, but generally follow the same principles). The following procedure is followed for each of the k “folds”:

* A model is trained using  of the folds as training data;
* The resulting model is validated on the remaining part of the data (i.e., it is used as a test set to compute a performance measure such as accuracy).

The performance measure reported by k-fold cross-validation is then the average of the values computed in the loop. This approach can be computationally expensive, but does not waste too much data (as is the case when fixing an arbitrary validation set), which is a major advantage in problems such as inverse inference where the number of samples is very small.


```python

```


```python
from IPython.display import Image
Image(filename="grid_search_cross_validation.png")
```


```python
# compute accuracy
clf.score(xtest, ytest)
```




    0.972027972027972



## Cross-validation with SVC


```python
from sklearn.model_selection import cross_val_score
```


```python
# note that all data can be used
clf = svm.SVC(gamma='scale')
scores = cross_val_score(clf, x, y, cv=5)
scores
```




    array([0.85217391, 0.89565217, 0.92920354, 0.94690265, 0.9380531 ])




```python
print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
```

    Accuracy: 0.91 (+/- 0.07)


41ce7b41dfcaa219097e7f459ea8c05eae87252c
ipynb
Jupyter Notebook
notebooks/.ipynb_checkpoints/5. Support Vector Machines-checkpoint.ipynb
gilberto-BE/aifi-pytorch
c7e0e1ff29c468c4c7bd68627fbad44486cf5ffa
MIT
notebooks/.ipynb_checkpoints/5. Support Vector Machines-checkpoint.ipynb
gilberto-BE/aifi-pytorch
c7e0e1ff29c468c4c7bd68627fbad44486cf5ffa
MIT
notebooks/.ipynb_checkpoints/5. Support Vector Machines-checkpoint.ipynb
gilberto-BE/aifi-pytorch
c7e0e1ff29c468c4c7bd68627fbad44486cf5ffa
MIT
Qwen/Qwen-72B
1. YES
2. YES