What is SVM?
- Machine Learning course
- Intermediate
- Lesson 25/112
- 5 min
SVM finds the hyperplane that separates classes with the widest margin.
What is an SVM?
A support vector machine (SVM) chooses, among the boundaries separating two classes, the one farthest from the classes. The training points closest to that boundary are called support vectors; the boundary's position depends only on them.
from sklearn.svm import SVC
m = SVC(kernel="linear").fit(X, y)
print(m.support_vectors_.shape) # support vector count x features
print(m.n_support_) # per classIf the other points were deleted the model wouldn't change; that is why an SVM is memory-efficient and relatively robust to outliers.
Strengths of SVMs
SVMs are strong on medium-sized data (up to a few tens of thousands of examples) with many features: text classification, bioinformatics. With the kernel trick they learn non-linear boundaries.
- Very scale-sensitive:
StandardScalerfirst. - Training time grows fast with the number of examples; for very large data
LinearSVCorSGDClassifieris preferred. - By default it produces a decision score, not a probability.
Practice Linear SVM
Train an SVC(kernel="linear") on separable two-cluster data. Print the number of support vectors (n_support_) and the predictions for [[0, 0], [4, 4]] on separate lines.
Starter code
import numpy as np
from sklearn.svm import SVC
X = np.array([[0, 0], [1, 0], [0, 1], [1, 1], [3, 3], [4, 3], [3, 4], [4, 4]])
y = np.array([0, 0, 0, 0, 1, 1, 1, 1])
# buraya yazSample solution
import numpy as np
from sklearn.svm import SVC
X = np.array([[0, 0], [1, 0], [0, 1], [1, 1], [3, 3], [4, 3], [3, 4], [4, 4]])
y = np.array([0, 0, 0, 0, 1, 1, 1, 1])
m = SVC(kernel="linear").fit(X, y)
print(m.n_support_)
print(m.predict([[0, 0], [4, 4]]))Expected output
[1 1] [0 1]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which points determine an SVM's boundary?
- The class means
- The support vectors Correct answer
- All points equally
- The points farthest from the boundary
Explanation: The points closest to the boundary define the margin; those far away have no effect.
2 Read the number of support vectors per class.
print(m.____)
print(m.n_support_)
Explanation: n_support_ gives the number of support vectors per class.
3 Match the terms.
| Term | Meaning |
|---|---|
support vector |
Point closest to the boundary |
support_vectors_ |
Their coordinates |
LinearSVC |
Fast for large data |
StandardScaler |
Required before SVM |