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:
- In two-dimensional space, a hyperplane is a straight line.
- In three-dimensional space, a hyperplane is a plane.
- In higher-dimensional space, a hyperplane is a hyperplane that divides the space.
Support vectors:
- Support vectors are the sample points closest to the hyperplane. These support vectors are crucial for defining the hyperplane.
- SVM selects the best hyperplane by maximizing the distance from the support vectors to the hyperplane (i.e., maximizing the margin).
Maximum margin:
- The goal of SVM is to maximize the classification margin, keeping the classification boundary as far as possible from the data points of both classes. This can effectively reduce the model's generalization error.
Kernel Trick:
- For non-linearly separable data, SVM uses a kernel function to map the data into a higher-dimensional space, where the data may be linearly separable.
- Common kernel functions include: linear kernel, polynomial kernel, radial basis function (RBF) kernel, etc.
SVM classification process
- Choose a hyperplane: find a hyperplane that maximizes the classification boundary.
- Train support vectors: through the SVM algorithm, select the sample points closest to the hyperplane as support vectors.
- Find the optimal hyperplane by maximizing the margin: select an optimal hyperplane that maximizes the margin.
- 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
)
(
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
)
(
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:
