Python SVM Example Code: A Practical Guide with Implementation

Python's Scikit-learn library is a treasure trove of machine learning algorithms, one of which is the Support Vector Machine (SVM). SVM is a supervised learning model commonly used for classification and regression analysis. Let's dive into Python SVM example code, exploring the algorithm's basic usage, and even delving into a simple classification example using the popular Iris dataset.

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

Before we jump into the coding part, let's briefly understand what SVM is. In simple terms, given a set of training samples, each marked as belonging to one or the other of two categories, an SVM training algorithm finds a hyperplane in an N-dimensional space that distinctly classifies the samples.

an image of a computer screen with cats on it and the words, python list method
an image of a computer screen with cats on it and the words, python list method

Setting Up the Environment

First, we need to import the necessary libraries. In our case, we mainly require pandas for data manipulation, sklearn for the SVM model and other utilities, and seaborn with matplotlib for visualization.

Emojis in python
Emojis in python

Next, we load the Iris dataset, which comes pre-bundled with scikit-learn. Let's print the first 5 rows to understand its structure.

Importing Libraries and Loading the Dataset

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

import pandas as pd import numpy as np from sklearn import datasets import matplotlib.pyplot as plt import seaborn as sns iris = datasets.load_iris() df = pd.DataFrame(data=np.c_[iris['data'], iris['target']], columns= iris['feature_names'] + ['target']) print(df.head())

Exploring the Dataset

To further understand the dataset, we can create a pairplot using seaborn's pairplot function. This will give us a visual overview of the data, including the distribution of features and the correlation between variables.

Preparing the Data for SVM

a poster with the words string method in python
a poster with the words string method in python

SVM, like many other machine learning algorithms, requires the target variable to be integers. In our Iris dataset, the target variable is already integers (0, 1, 2), representing the three different types of iris flowers. However, we need to separate the features and the target.

Separating Features and Target

X = df[iris['feature_names']] y = df['target']

We've now prepared our data for the SVM model. Let's proceed to build and train our SVM model.

25+ Examples of Real Python Programming Code - Skillcrush
25+ Examples of Real Python Programming Code - Skillcrush

Building and Training the SVM Model

We use the SVC ( Support Vector Classifier ) method from sklearn.svm to instantiate our SVM model. Next, we fit the model using our features and target data. Here's a simple, unoptimized SVM model for starters.

python aesthetic
python aesthetic
Python
Python
the calendar in python code is shown with red arrows pointing to it and black background
the calendar in python code is shown with red arrows pointing to it and black background
Python syntax cheat sheet infographic
Python syntax cheat sheet infographic
Python If-Else Cheat Sheet
Python If-Else Cheat Sheet
How to read Multiple Columns from CSV File in Python? With Source Code
How to read Multiple Columns from CSV File in Python? With Source Code
a poster with the words python and symbols
a poster with the words python and symbols
Simple Python code for snake game with images
Simple Python code for snake game with images
an image of a computer screen with the text'generation ascii art in python '
an image of a computer screen with the text'generation ascii art in python '
the diagram shows how to use python commands for web pages and other contents, including data
the diagram shows how to use python commands for web pages and other contents, including data
an info sheet with the words 10 python one - liners that will blow your mind
an info sheet with the words 10 python one - liners that will blow your mind
Python Syntax Explained Simply 🐍
Python Syntax Explained Simply 🐍
python coding example - triangle pattern
python coding example - triangle pattern
a screenshot of a computer screen with the words python string method in front of it
a screenshot of a computer screen with the words python string method in front of it
Coding For Beginners Python - Learn the Basics - Basic Syntax
Coding For Beginners Python - Learn the Basics - Basic Syntax
wifi password 👌🚷
wifi password 👌🚷
qr code generator using python
qr code generator using python
Best Practices to Write Clean Python Code
Best Practices to Write Clean Python Code
TURTLE DESIGN using Python
TURTLE DESIGN using Python

Instantiating and Fitting the Model

from sklearn.svm import SVC clf = SVC() clf.fit(X, y)

Now we have our basic SVM model. However, this is far from a production-ready model. In practice, we would need to consider aspects like hyperparameter tuning, cross-validation, feature selection, etc. But for now, let's get some predictions from our model.

Making Predictions

We can use our model to predict the species of an iris flower by using its sepal length, sepal width, petal length, and petal width. Let's input a few examples and see what the model predicts.

Making Predictions

new_data = [[5.1, 3.5, 1.4, 0.2], [6.7, 3.1, 5.6, 2.4], [5.9, 3.0, 5.1, 1.8]] predictions = clf.predict(new_data) print(predictions)

Remember, the predictions are based on the numbers 0, 1, 2, corresponding to the three classes of iris flowers (setosa, versicolor, virginica).

And there you have it! A simple Python SVM example code. Of course, in real-world scenarios, you'd have to consider a lot more aspects, like data preprocessing, hyperparameter tuning, evaluating the model's performance, and more. But hopefully, this gives you a solid starting point to begin your journey with SVM in Python.

Related Articles

Postgresql Python Connect To Postgresql Database Server Python Numpy Sample Simple Python Code Examples For Beginners Kafka Code Example Python Backend Example Github Kafka Python Simple Example Python Compiler Save Random Sample From List Python Numpy Two Sample Binomial Test Python Snowflake Python Examples