Python SVM Example: Step-by-Step Guide with Code Snippets

Support Vector Machines (SVM) is a powerful machine learning algorithm widely used in classification and regression problems. Python, with its extensive library support, provides a seamless environment to implement SVM. In this comprehensive guide, we will explore SVM implementation in Python using the popular library, Scikit-learn.

Python Data Structures Cheat Sheet for Beginners (Lists, Tuples, Sets & Dictionaries)
Python Data Structures Cheat Sheet for Beginners (Lists, Tuples, Sets & Dictionaries)

Before diving into the example, let's understand SVM in brief. SVM finds a hyperplane that best divides the data into different classes. It's particularly useful when you have a dataset that is not linearly separable, thanks to the kernel trick.

Python Sys Argv in Simple Words with Examples
Python Sys Argv in Simple Words with Examples

Installing and Importing Required Libraries

First, you need to install the required libraries. You can install Scikit-learn and Matplotlib using pip:

a book cover with the title'basic guide to python sytax '
a book cover with the title'basic guide to python sytax '

Using pip to install libraries
!pip install -U scikit-learn matplotlib

Importing Libraries

Now, let's import the required libraries:

All Important Python Functions for Beginners (Complete Cheat Sheet)
All Important Python Functions for Beginners (Complete Cheat Sheet)

Importing necessary libraries
from sklearn import datasets
from sklearn import svm
import matplotlib.pyplot as plt

Next, we'll load the iris dataset which comes preloaded with Scikit-learn:

Loading Dataset

The iris dataset comprises 150 random samples of iris flowers from three different species.

Complete Python Built-in Functions with Examples
Complete Python Built-in Functions with Examples

Loading Iris dataset
iris = datasets.load_iris()
X = iris.data
y = iris.target

Creating the SVM Model

Having loaded the dataset, let's create an SVM classifier. We'll use the SVC (Support Vector Classifier) class from Scikit-learn.

Creating the SVC Classifier

the statistics module in python 1 calculating mean important statistics data = 1, 2, 3, 4, 5,
the statistics module in python 1 calculating mean important statistics data = 1, 2, 3, 4, 5,

The SVC class has several parameters like C (regularization parameter), kernel (type of kernel function to be used), gamma (kernel coefficient for 'rbf', 'poly', and 'sigmoid'), and degree (degree of the polynomial kernel function). We'll use the default values for this example.

Initiating SVC Classifier
clf = svm.SVC()

Now, let's train our model using our dataset:

three different types of python programming
three different types of python programming
Python
Python
Python Dotenv (Explanation with Examples)
Python Dotenv (Explanation with Examples)
Python Programming, Python
Python Programming, Python
python coding example - triangle pattern
python coding example - triangle pattern
Python syntax cheat sheet infographic
Python syntax cheat sheet infographic
How to Print Exception in Python with Examples
How to Print Exception in Python with Examples
a poster with the words string method in python
a poster with the words string method in python
seaborn
seaborn
Python List Comprehension Cheat Sheet 📌
Python List Comprehension Cheat Sheet 📌
Python Remove Substring with Examples
Python Remove Substring with Examples
Python Programming Aesthetic: Syntax You’ll Love
Python Programming Aesthetic: Syntax You’ll Love
Python Unit 3 Cheat Sheet 🐍 | Functions, Arguments, Lambda & Modules (AKTU)
Python Unit 3 Cheat Sheet 🐍 | Functions, Arguments, Lambda & Modules (AKTU)
a poster with the words python sylabus written in orange and black on it
a poster with the words python sylabus written in orange and black on it
matplotlib
matplotlib
PYTHON BASICS
PYTHON BASICS
the sum all numbers in a list python
the sum all numbers in a list python
| Pythonista Planet
| Pythonista Planet
Data Types In Python
Data Types In Python
Python Lists in Python Programming
Python Lists in Python Programming

Training the SVM model
clf.fit(X, y)

Predicting the Results

After training, we can use the model to predict the target classes for new data:

Making predictions
predicted = clf.predict(X)

Visualizing the Results

Let's visualize the decision boundary of our SVM classifier. For the Iris dataset, we can visualize it in a 2D space using the first two features.

2D Space Visualization

Scikit-learn provides a tool, "plot_decision_region", which we can use to visualize the decision boundary:

Plotting Decision Region
from mlxtend.plotting import plot_decision_region
plot_decision_region(X=X, y=y, clf=clf, legend=2)

This article provided an extensive example of using SVM in Python. To dive deeper, you can experiment with different kernels, parameters, and datasets. Happy coding!

Related Articles

Python Backend Example Python Connect To Postgresql Example Kafka Python Source Code Python Sample Code To Read A File Sample Python Code For Vscode Python Numpy Sample Snowflake Python Examples Sample Without Replacement Python Numpy Sample Python Class Code How To Connect Python With Postgresql Database