The Wayback Machine - https://web.archive.org/web/20240824062522/https://www.geeksforgeeks.org/classifying-data-using-support-vector-machinessvms-in-python/
Open In App

Classifying data using Support Vector Machines(SVMs) in Python

Last Updated : 01 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Introduction to SVMs: In machine learning, support vector machines (SVMs, also support vector networks) are supervised learning models with associated learning algorithms that analyze data used for classification and regression analysis. A Support Vector Machine (SVM) is a discriminative classifier formally defined by a separating hyperplane. In other words, given labeled training data (supervised learning), the algorithm outputs an optimal hyperplane which categorizes new examples.

What is Support Vector Machine?

An SVM model is a representation of the examples as points in space, mapped so that the examples of the separate categories are divided by a clear gap that is as wide as possible. In addition to performing linear classification, SVMs can efficiently perform a non-linear classification, implicitly mapping their inputs into high-dimensional feature spaces.

What does SVM do?

Given a set of training examples, each marked as belonging to one or the other of two categories, an SVM training algorithm builds a model that assigns new examples to one category or the other, making it a non-probabilistic binary linear classifier. Let you have basic understandings from this article before you proceed further. Here I’ll discuss an example about SVM classification of cancer UCI datasets using machine learning tools i.e. scikit-learn compatible with Python. Pre-requisites: Numpy, Pandas, matplot-lib, scikit-learn Let’s have a quick example of support vector classification. First we need to create a dataset: 

python3




# importing scikit learn with make_blobs
from sklearn.datasets import make_blobs
 
# creating datasets X containing n_samples
# Y containing two classes
X, Y = make_blobs(n_samples=500, centers=2,
                  random_state=0, cluster_std=0.40)
import matplotlib.pyplot as plt
# plotting scatters
plt.scatter(X[:, 0], X[:, 1], c=Y, s=50, cmap='spring');
plt.show()


Output: g2 What Support vector machines do, is to not only draw a line between two classes here, but consider a region about the line of some given width. Here’s an example of what it can look like: 

python3




# creating linspace between -1 to 3.5
xfit = np.linspace(-1, 3.5)
 
# plotting scatter
plt.scatter(X[:, 0], X[:, 1], c=Y, s=50, cmap='spring')
 
# plot a line between the different sets of data
for m, b, d in [(1, 0.65, 0.33), (0.5, 1.6, 0.55), (-0.2, 2.9, 0.2)]:
    yfit = m * xfit + b
    plt.plot(xfit, yfit, '-k')
    plt.fill_between(xfit, yfit - d, yfit + d, edgecolor='none',
    color='#AAAAAA', alpha=0.4)
 
plt.xlim(-1, 3.5);
plt.show()


g3

Importing datasets

This is the intuition of support vector machines, which optimize a linear discriminant model representing the perpendicular distance between the datasets. Now let’s train the classifier using our training data. Before training, we need to import cancer datasets as csv file where we will train two features out of all features. 

python3




# importing required libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
 
# reading csv file and extracting class column to y.
x = pd.read_csv("C:\...\cancer.csv")
a = np.array(x)
y  = a[:,30] # classes having 0 and 1
 
# extracting two features
x = np.column_stack((x.malignant,x.benign))
 
# 569 samples and 2 features
x.shape
 
print (x),(y)


[[  122.8   1001.  ]
[ 132.9 1326. ]
[ 130. 1203. ]
...,
[ 108.3 858.1 ]
[ 140.1 1265. ]
[ 47.92 181. ]]

array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 1., 1., 1., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0.,
0., 0., 0., 0., 0., 0., 0., 1., 0., 1., 1., 1., 1.,
1., 0., 0., 1., 0., 0., 1., 1., 1., 1., 0., 1., ....,
1.])

Fitting a Support Vector Machine

Now we’ll fit a Support Vector Machine Classifier to these points. While the mathematical details of the likelihood model are interesting, we’ll let read about those elsewhere. Instead, we’ll just treat the scikit-learn algorithm as a black box which accomplishes the above task. 

python3




# import support vector classifier
# "Support Vector Classifier"
from sklearn.svm import SVC 
clf = SVC(kernel='linear')
 
# fitting x samples and y classes
clf.fit(x, y)


After being fitted, the model can then be used to predict new values: 

python3




clf.predict([[120, 990]])
 
clf.predict([[85, 550]])


array([ 0.])
array([ 1.])

Let’s have a look on the graph how does this show. g1 This is obtained by analyzing the data taken and pre-processing methods to make optimal hyperplanes using matplotlib func If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.



Previous Article
Next Article

Similar Reads

Classifying data using Support Vector Machines(SVMs) in R
In machine learning, Support vector machines (SVM) are supervised learning models with associated learning algorithms that analyze data used for classification and regression analysis. It is mostly used in classification problems. In this algorithm, each data item is plotted as a point in n-dimensional space (where n is a number of features), with
5 min read
Visualizing Support Vector Machines (SVM) using Python
Support Vector Machines (SVMs) are powerful supervised learning models used for classification and regression tasks. A key factor behind their popularity is their ability to handle both linear and non-linear data effectively. In this article, we will explore visualizing SVMs using Python and popular libraries like scikit-learn and Matplotlib. Suppo
6 min read
Predicting Stock Price Direction using Support Vector Machines
We are going to implement an End-to-End project using Support Vector Machines to live Trade For us. You Probably must have Heard of the term stock market which is known to have made the lives of thousands and to have destroyed the lives of millions. If you are not familiar with the stock market you can surf some basic Stuff about markets. Tools and
5 min read
Introduction to Support Vector Machines (SVM)
INTRODUCTION:Support Vector Machines (SVMs) are a type of supervised learning algorithm that can be used for classification or regression tasks. The main idea behind SVMs is to find a hyperplane that maximally separates the different classes in the training data. This is done by finding the hyperplane that has the largest margin, which is defined a
6 min read
What are advantages of Artificial Neural Networks over Support Vector Machines?
Answer: Artificial Neural Networks offer greater flexibility in handling complex, nonlinear relationships compared to Support Vector Machines.Artificial Neural Networks (ANNs) and Support Vector Machines (SVMs) are two widely used machine learning algorithms, each with its strengths and weaknesses. While both are powerful tools for classification a
2 min read
Support Vector Machines vs Neural Networks
Support Vector Machine (SVM) is a powerful machine learning algorithm adopted for linear or nonlinear classification, regression, and even outlier detection tasks and Neural networks, A machine learning (ML) model is made to simulate the structure and operations of the human brain. With a linear rise in the input size, an SVM's number of parameters
9 min read
Comparing Support Vector Machines and Decision Trees for Text Classification
Support Vector Machines (SVMs) and Decision Trees are both popular algorithms for text classification, but they have different characteristics and are suitable for different types of problems. Why is model selection important in Text Classification?Selecting the ideal model for text classification resembles selecting the ideal tool for a task – it'
8 min read
Understanding One-Class Support Vector Machines
Support Vector Machine is a popular supervised machine learning algorithm. it is used for both classifications and regression. In this article, we will discuss One-Class Support Vector Machines model. One-Class Support Vector MachinesOne-Class Support Vector Machine is a special variant of Support Vector Machine that is primarily designed for outli
10 min read
Hinge-loss & relationship with Support Vector Machines
Here we will be discussing the role of Hinge loss in SVM hard margin and soft margin classifiers, understanding the optimization process, and kernel trick. Support Vector Machine(SVM)Support Vector Machine(SVM) is a supervised machine learning algorithm for classification and regression. Let us use the binary classification case to understand the H
12 min read
Optimal feature selection for Support Vector Machines
In machine learning, feature selection is an essential phase, particularly when working with high-dimensional datasets. Although Support Vector Machines (SVMs) are strong classifiers, the features that are used might affect how well they perform. This post will discuss the idea of ideal feature selection for support vector machines (SVMs), its sign
7 min read
ML | Classifying Data using an Auto-encoder
Prerequisites: Building an Auto-encoder This article will demonstrate how to use an Auto-encoder to classify data. The data used below is the Credit Card transactions data to predict whether a given transaction is fraudulent or not. Step 1: Loading the required libraries import pandas as pd import numpy as np from sklearn.model_selection import tra
5 min read
Classifying Sonar Data: Rocks vs. Mines Using Machine Learning
The objective of this project is to classify sonar data to differentiate between rocks and mines using machine learning techniques. Sonar data, collected through sound waves, is processed to detect underwater objects. Machine learning models can analyze this data to predict whether an object is a rock or a mine. Table of Content Classification Proj
7 min read
How to Choose the Best Kernel Function for SVMs
Support Vector Machines (SVMs) are powerful supervised learning models that can be used for classification, regression, and outlier detection tasks. What are kernels in SVM?Kernels in Support Vector Machines (SVMs) are functions that calculate the similarity of pairs of data points in a high-dimensional space. They allow SVMs to discover complex, n
7 min read
Classifying Clothing Images in Python
Everywhere in social media image classification takes place from picking profile photos on Facebook, Instagram to categorizing clothes images in shopping apps like Myntra, Amazon, Flipkart, etc. Classification has become an integral part of any e-commerce platform. Classification is also used on identifying criminal faces in law and social networki
6 min read
Image classification using Support Vector Machine (SVM) in Python
Support Vector Machines (SVMs) are a type of supervised machine learning algorithm that can be used for classification and regression tasks. In this article, we will focus on using SVMs for image classification. When a computer processes an image, it perceives it as a two-dimensional array of pixels. The size of the array corresponds to the resolut
9 min read
Project | kNN | Classifying IRIS Dataset
Introduction | kNN Algorithm Statistical learning refers to a collection of mathematical and computation tools to understand data.In what is often called supervised learning, the goal is to estimate or predict an output based on one or more inputs.The inputs have many names, like predictors, independent variables, features, and variables being call
8 min read
Support Vector Regression (SVR) using Linear and Non-Linear Kernels in Scikit Learn
Support vector regression (SVR) is a type of support vector machine (SVM) that is used for regression tasks. It tries to find a function that best predicts the continuous output value for a given input value. SVR can use both linear and non-linear kernels. A linear kernel is a simple dot product between two input vectors, while a non-linear kernel
5 min read
Heart Disease Prediction using Support Vector Machine
Heart disease is a significant health concern worldwide, and early detection plays a crucial role in effective treatment and prevention. Machine learning algorithms, such as Support Vector Machines (SVM), have shown promising results in predicting heart disease based on patient data. SVM stands for Support Vector Machine are a set of supervised lea
4 min read
Support vector machine in Machine Learning
In this article, we are going to discuss the support vector machine in machine learning. We will also cover the advantages and disadvantages and application for the same. Let's discuss them one by one. Support Vector Machines : Support vector machine is a supervised learning system and is used for classification and regression problems. Support vec
9 min read
Major Kernel Functions in Support Vector Machine (SVM)
Kernel Function is a method used to take data as input and transform it into the required form of processing data. "Kernel" is used due to a set of mathematical functions used in Support Vector Machine providing the window to manipulate the data. So, Kernel Function generally transforms the training set of data so that a non-linear decision surface
2 min read
Differentiate between Support Vector Machine and Logistic Regression
Logistic Regression: It is a classification model which is used to predict the odds in favour of a particular event. The odds ratio represents the positive event which we want to predict, for example, how likely a sample has breast cancer/ how likely is it for an individual to become diabetic in future. It used the sigmoid function to convert an in
4 min read
Dual Support Vector Machine
Pre-requisite: Separating Hyperplanes in SVM The Lagrange multiplier equation for the support vector machine. The equation of that can be given by: [Tex]\underset{\vec{w},b}{min} \underset{\vec{a}\geq 0}{max} \frac{1}{2}\left \| w \right \|^{2} - \sum_{j}a_j\left [ \left ( \vec{w} \cdot \vec{x}_{j} \right )y_j - 1 \right ][/Tex] Now, according to t
6 min read
Random Forest vs Support Vector Machine vs Neural Network
Machine learning boasts diverse algorithms, each with its strengths and weaknesses. Three prominent are – Random Forest, Support Vector Machines (SVMs), and Neural Networks – stand out for their versatility and effectiveness. But when do you we choose one over the others? In this article, we'll delve into the key differences between these three alg
5 min read
Support Vector Machine vs Extreme Gradient Boosting
Support Vector Machine (SVM) and Extreme Gradient Boosting (XGBoost) are both powerful machine learning algorithms widely used for classification and regression tasks. They belong to different families of algorithms and have distinct characteristics in terms of their approach to learning, model type, and performance. In this article, we discuss abo
4 min read
Time Series Forecasting with Support Vector Regression
Time series forecasting is a critical aspect of data analysis, with applications spanning from financial markets to weather predictions. In recent years, Support Vector Regression (SVR) has emerged as a powerful tool for time series forecasting due to its ability to handle nonlinear relationships and high-dimensional data. In this project, we'll de
11 min read
Support Vector Machine (SVM) for Anomaly Detection
Support Vector Machines (SVMs) are powerful supervised learning models that can also be used for anomaly detection. They can be effective for anomaly detection because they find the hyperplane that best separates the normal data points from the anomalies. Mainly, the one-class support vector machine is an unsupervised model for anomaly or outlier d
8 min read
Kernel Trick in Support Vector Classification
Support Vector Machines (SVMs) have proven to be a powerful and versatile tool for classification tasks. A key component that significantly enhances the capabilities of SVMs, particularly in dealing with non-linear data, is the Kernel Trick. This article delves into the intricacies of the Kernel Trick, its motivation, implementation, and practical
3 min read
Support Vector Machine (SVM) Algorithm
Support Vector Machine (SVM) is a powerful machine learning algorithm used for linear or nonlinear classification, regression, and even outlier detection tasks. SVMs can be used for a variety of tasks, such as text classification, image classification, spam detection, handwriting identification, gene expression analysis, face detection, and anomaly
10 min read
Variable importance for support vector machine and naive Bayes classifiers in R
Understanding the importance of variables in a model is crucial for interpreting and improving the model's performance. Variable importance helps identify which features contribute most to the prediction. In this article, we will explore how to assess variable importance for Support Vector Machine (SVM) and Naive Bayes classifiers in R Programming
3 min read
Underrated and Implementing Nu-Support Vector Classification (NuSVC)
Machine learning (ML) is a vast field, with certain algorithms often overshadowing others due to their widespread use and popularity. However, some lesser-known algorithms offer unique advantages and deserve more attention. This article delves into some underrated ML algorithms, with a special focus on Nu-Support Vector Classification (NuSVC). We w
6 min read
three90RightbarBannerImg