Machine Learning from Scratch – Day 12: Understanding Support Vector Machines (SVM)
Understanding Support Vector Machines (SVM)
Series: Machine Learning From Scratch (18 articles)
- …
- 12Machine Learning from Scratch – Day 12: Understanding Support Vector Machines (SVM) This article
Machine Learning from Scratch – Day 12: Understanding Support Vector Machines (SVM)
Introduction
In our previous article, we explored Naive Bayes, a probabilistic machine learning algorithm that uses Bayes' Theorem to classify data.
Today, we are going to understand another powerful supervised learning algorithm: Support Vector Machines (SVM).
Imagine you have a dataset containing two categories of data points: red circles and blue squares.
Your task is to draw a line that separates these two groups.
You might find several lines that successfully separate them. But which line should you choose?
SVM solves this problem by finding a decision boundary that separates the classes while maximizing the distance between the boundary and the closest data points.
This idea makes SVM particularly interesting for classification problems.
1. What is Support Vector Machine?
Support Vector Machine (SVM) is a supervised machine learning algorithm mainly used for classification, although it can also be used for regression.
Its primary objective is to find an optimal decision boundary that separates different classes.
This boundary is called a hyperplane.
Depending on the number of dimensions:
- In 2D, the hyperplane is a line.
- In 3D, the hyperplane is a plane.
- In higher dimensions, it is called a hyperplane.
SVM tries to find the hyperplane that provides the maximum margin between the classes.
2. Understanding Hyperplanes
A hyperplane is a decision boundary that separates data points belonging to different classes.
For a two-dimensional dataset, the equation of a straight decision boundary is:
w₁x₁ + w₂x₂ + b = 0
Where:
- x₁ and x₂ represent input features.
- w₁ and w₂ represent weights.
- b represents the bias term.
The model uses this boundary to classify new data points.
For example:
- Points on one side may belong to Class A.
- Points on the other side may belong to Class B.
The goal is to find a boundary that separates the classes as effectively as possible.
3. What Are Support Vectors?
The name Support Vector Machine comes from an important concept called support vectors.
Support vectors are the data points closest to the decision boundary.
These points play a major role in determining the position and orientation of the optimal hyperplane.
Changing or moving the support vectors can change the decision boundary.
However, moving a data point far away from the margin generally does not affect the fitted boundary.
In simple terms, support vectors are the critical data points that help define the separation between classes.
4. Understanding Margin
The margin is the distance between the decision boundary and the nearest data points from each class.
SVM attempts to maximize this margin.
Why?
A larger margin can help the model generalize better to unseen data, although it does not guarantee better performance in every dataset.
There are two important concepts:
Hard Margin SVM
- Attempts to separate classes perfectly.
- Does not allow training misclassifications.
- Works best when data is linearly separable.
- Can be sensitive to noise and outliers.
Soft Margin SVM
- Allows some margin violations and potentially some misclassifications.
- Provides a balance between maximizing the margin and minimizing classification errors.
- Usually more practical for real-world datasets.
The parameter C controls the trade-off:
- Large C: Penalizes margin violations more heavily.
- Small C: Allows more violations in exchange for a wider margin.
5. Types of SVM
SVM can handle different types of decision boundaries.
1. Linear SVM
Linear SVM is used when classes can be separated reasonably well using a straight decision boundary.
Example:
Classifying two groups of customers based on two numerical features when their patterns are approximately linearly separable.
2. Non-Linear SVM
Sometimes, data cannot be separated effectively using a straight line or hyperplane.
In such situations, SVM can use kernel functions to model nonlinear decision boundaries.
For example, consider a dataset where one class is surrounded by another class.
A straight line cannot separate them effectively, but a nonlinear boundary may work.
6. Understanding the Kernel Trick
The kernel trick is one of the most powerful features of SVM.
It allows SVM to learn nonlinear decision boundaries without explicitly calculating the coordinates of every data point in a higher-dimensional feature space.
Some commonly used kernel functions include:
1. Linear Kernel
Used when a linear decision boundary is suitable.
2. Polynomial Kernel
Can model relationships using polynomial combinations of features.
3. RBF (Radial Basis Function) Kernel
A popular choice for nonlinear classification problems.
4. Sigmoid Kernel
Uses a sigmoid-shaped kernel function and can behave similarly to certain neural network activation functions.
The RBF kernel is often a useful starting point when the relationship between features and classes is nonlinear.
7. Important SVM Parameters
When implementing SVM using Scikit-learn, you will commonly encounter these parameters:
Parameter | Purpose |
|---|---|
C | Controls the penalty for margin violations |
kernel | Specifies the kernel function |
gamma | Controls the influence range of individual training points for RBF, polynomial, and sigmoid kernels |
degree | Specifies the polynomial degree when using the polynomial kernel |
Understanding these parameters helps us tune the model for better performance.
8. Implementing SVM Using Python
Now let's implement SVM using Scikit-learn.
We will use the Iris dataset to classify flower species.
Step 1: Import libraries
from sklearn.datasets import load_irisfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScalerfrom sklearn.svm import SVCfrom sklearn.metrics import accuracy_score, classification_reportStep 2: Load the dataset
iris = load_iris()
X = iris.datay = iris.targetThe dataset contains four numerical features and three flower categories.
Step 3: Split the dataset
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y)We use 80% of the data for training and 20% for testing.
Step 4: Apply feature scaling
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)X_test = scaler.transform(X_test)Feature scaling is particularly important for SVM because the scale of features can influence the margin and kernel calculations.
Step 5: Create and train the model
model = SVC( kernel="rbf", C=1.0, gamma="scale")
model.fit(X_train, y_train)Here:
-
kernel="rbf"selects the Radial Basis Function kernel.
-
C=1.0controls the penalty for margin violations.
-
gamma="scale"lets Scikit-learn calculate a suitable gamma value based on the training data.
Step 6: Make predictions
y_pred = model.predict(X_test)The model predicts the flower species for the testing data.
Step 7: Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
print(classification_report(y_test, y_pred))The classification report provides precision, recall, and F1-score for each class.
The exact accuracy depends on the dataset split and model configuration.
9. Advantages and Disadvantages of SVM
Advantages | Disadvantages |
|---|---|
Effective in high-dimensional feature spaces | Can be computationally expensive on large datasets |
Supports linear and nonlinear classification | Requires careful parameter tuning |
Uses support vectors to define the decision boundary | Sensitive to feature scaling |
Can work well with limited training data | Choosing the right kernel can be difficult |
Supports classification and regression | Less interpretable than simple decision trees |
10. Real-World Applications of SVM
SVM is used in several machine learning applications.
1. Image Classification
Can classify images into categories using extracted image features.
2. Text Classification
Can categorize documents, emails, and news articles.
3. Handwriting Recognition
Can classify handwritten digits and characters.
4. Medical Data Classification
Can support classification tasks involving medical measurements and extracted features, subject to appropriate clinical validation.
5. Face Detection
Has been used in computer vision systems to classify image regions as containing a face or not.
11. Key Takeaways
Let's summarize what we learned today:
- SVM stands for Support Vector Machine.
- It is a supervised machine learning algorithm.
- It is mainly used for classification but also supports regression.
- A hyperplane separates different classes.
- Support vectors are the closest data points to the decision boundary.
- SVM tries to maximize the margin.
- Kernel functions help model nonlinear decision boundaries.
- C and gamma are important parameters when tuning SVM models.
SVM teaches us an important machine learning concept: instead of simply finding a boundary that separates classes, we can search for a boundary that maximizes the margin around it.
Coming Next – Day 13: Understanding K-Means Clustering
So far, we have explored supervised learning algorithms that use labeled data.
In the next article, we will move into unsupervised learning and understand K-Means Clustering.
We will explore how machines group similar data points without being given predefined labels, how centroids work, and how to implement K-Means using Python.
Series: Machine Learning From Scratch (18 articles)
- …
- 12Machine Learning from Scratch – Day 12: Understanding Support Vector Machines (SVM) This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article