Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Support Vector Machine

Support Vector Machine

Support Vector Machine (SVM for short) is a supervised learning algorithm, mainly used for classification and regression problems.

The core idea of SVM is to find an optimal hyperplane that separates data of different classes. This hyperplane must not only correctly classify the data, but also maximize the margin between the two classes.

Hyperplane:

Support vectors:

Maximum margin:

Kernel Trick:

SVM classification process

  1. Choose a hyperplane: find a hyperplane that maximizes the classification boundary.
  2. Train support vectors: through the SVM algorithm, select the sample points closest to the hyperplane as support vectors.
  3. Find the optimal hyperplane by maximizing the margin: select an optimal hyperplane that maximizes the margin.
  4. Handle nonlinear problems with kernel functions: solve non-linearly separable problems by mapping data into a high-dimensional space via a kernel function.

Implementing SVM with Python

Next, we will use the scikit-learn library in Python to implement a simple SVM classifier.

1. Install the Necessary Libraries

First, make sure you have installed thescikit-learnlibrary. If not, you can install it with the following command:



pip install scikit-learn

2. Import libraries

Example

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

from

sklearn

import

svm

,

datasets

from

sklearn.

model_selection

import

train_test_split

from

sklearn.

metrics

import

accuracy_score

3. Load the dataset

We will usescikit-learnthe built-in Iris dataset.

Example

Load the Iris dataset

iris

=

datasets.

load_iris

(

)

X

=

iris.

data

[

:

,

:

2

]

 

Use only the first two features

y

=

iris.

target

4. Split into training and test sets

Example

Split the dataset into training and test sets

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.3

,

random_state

=

42

)

5. Train the SVM model

Example

Create an SVM classifier

clf

=

svm.

SVC

(

kernel

=

'linear'

)

 

Use a linear kernel function

Train the model

clf.

fit

(

X_train

,

y_train

)

6. Prediction and evaluation

Example

Make predictions on the test set

y_pred

=

clf.

predict

(

X_test

)

Compute accuracy

accuracy

=

accuracy_score

(

y_test

,

y_pred

)

print

(

f

"Model Accuracy: {accuracy:.2f}"

)

7. Visualize the results

Example

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

from

sklearn

import

svm

,

datasets

from

sklearn.

model_selection

import

train_test_split

from

sklearn.

metrics

import

accuracy_score

Load the Iris dataset

iris

=

datasets.

load_iris

(

)

X

=

iris.

data

[

:

,

:

2

]

 

Use only the first two features

y

=

iris.

target

Split the dataset into training and test sets

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.3

,

random_state

=

42

)

Create an SVM classifier

clf

=

svm.

SVC

(

kernel

=

'linear'

)

 

Use a linear kernel function

Train the model

clf.

fit

(

X_train

,

y_train

)

Make predictions on the test set

y_pred

=

clf.

predict

(

X_test

)

Compute accuracy

accuracy

=

accuracy_score

(

y_test

,

y_pred

)

print

(

f

"Model Accuracy: {accuracy:.2f}"

)

Plot the decision boundary

def

plot_decision_boundary

(

X

,

y

,

model

)

:

    h

=

.02

 

Grid step size

    x_min

,

x_max

=

X

[

:

,

0

]

.

min

(

)

1

,

X

[

:

,

0

]

.

max

(

)

1

    y_min

,

y_max

=

X

[

:

,

1

]

.

min

(

)

1

,

X

[

:

,

1

]

.

max

(

)

1

    xx

,

yy

=

np.

meshgrid

(

np.

arange

(

x_min

,

x_max

,

h

)

,

                         np.

arange

(

y_min

,

y_max

,

h

)

)

    Z

=

model.

predict

(

np.

c_

[

xx.

ravel

(

)

,

yy.

ravel

(

)

]

)

    Z

=

Z.

reshape

(

xx.

shape

)

    plt.

contourf

(

xx

,

yy

,

Z

,

alpha

=

0.8

)

    plt.

scatter

(

X

[

:

,

0

]

,

X

[

:

,

1

]

,

c

=

y

,

edgecolors

=

'k'

,

marker

=

'o'

)

    plt.

xlabel

(

'Sepal length'

)

    plt.

ylabel

(

'Sepal width'

)

    plt.

title

(

'SVM Decision Boundary'

)

    plt.

show

(

)

plot_decision_boundary

(

X_train

,

y_train

,

clf

)

Running the above code produces the following output:

模型准确率: 0.80

The image is displayed as: