The Wayback Machine - https://web.archive.org/web/20240930203331/https://www.geeksforgeeks.org/creating-linear-kernel-svm-in-python/
Open In App

Creating linear kernel SVM in Python

Last Updated : 20 Jun, 2018
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite: SVM

Let’s create a Linear Kernel SVM using the sklearn library of Python and the Iris Dataset that can be found in the dataset library of Python.

Linear Kernel is used when the data is Linearly separable, that is, it can be separated using a single Line. It is one of the most common kernels to be used. It is mostly used when there are a Large number of Features in a particular Data Set. One of the examples where there are a lot of features, is Text Classification, as each alphabet is a new feature. So we mostly use Linear Kernel in Text Classification.

Note: Internet Connection must be stable while running the below code because it involves downloading data.

In the above image, there are two set of features “Blue” features and the “Yellow” Features. Since these can be easily separated or in other words, they are linearly separable, so the Linear Kernel can be used here.

Advantages of using Linear Kernel:

1. Training a SVM with a Linear Kernel is Faster than with any other Kernel.

2. When training a SVM with a Linear Kernel, only the optimisation of the C Regularisation parameter is required. On the other hand, when training with other kernels, there is a need to optimise the γ parameter which means that performing a grid search will usually take more time.




# Import the Libraries
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets
  
# Import some Data from the iris Data Set
iris = datasets.load_iris()
  
# Take only the first two features of Data.
# To avoid the slicing, Two-Dim Dataset can be used
  
X = iris.data[:, :2]
y = iris.target
  
# C is the SVM regularization parameter
C = 1.0 
  
# Create an Instance of SVM and Fit out the data.
# Data is not scaled so as to be able to plot the support vectors
svc = svm.SVC(kernel ='linear', C = 1).fit(X, y)
  
# create a mesh to plot
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
h = (x_max / x_min)/100
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
         np.arange(y_min, y_max, h))
  
# Plot the data for Proper Visual Representation
plt.subplot(1, 1, 1)
  
# Predict the result by giving Data to the model
Z = svc.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, cmap = plt.cm.Paired, alpha = 0.8)
  
plt.scatter(X[:, 0], X[:, 1], c = y, cmap = plt.cm.Paired)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.xlim(xx.min(), xx.max())
plt.title('SVC with linear kernel')
  
# Output the Plot
plt.show()


Output:

Here all the features are separated using simple lines, thus representing the Linear Kernel.



Similar Reads

Stop the Jupyter Kernel if Kernel is not responding
Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations, and narrative text. Google Colab and Kaggle Notebook are inspired by it. Data transformation and cleaning, statistical modelling, data visualization, machine learning, and many other applications are ju
7 min read
RBF SVM Parameters in Scikit Learn
Scikit Learn is a popular machine-learning library in Python, and it provides a powerful implementation of Support Vector Machines (SVMs) with the Radial Basis Function (RBF) kernel. RBF kernel is a popular choice for SVM because it can handle non-linear decision boundaries, making it suitable for a wide range of classification tasks. When using RB
9 min read
Python PIL | Kernel() method
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageFilter module contains definitions for a pre-defined set of filters, which can be used with the Image.filter() method. PIL.ImageFilter.Kernel() Create a convolution kernel. The current version only supports 3x3 and 5x5 integer and float
2 min read
How to Add a Python 3 Kernel to Jupyter IPython
In this article, we will cover how to install the IPython kernel and integrate it with Jupyter Notebook. We will look at what is Jupyter notebook, followed by a detailed step-by-step tutorial to install IPython kernel and its integration with Jupyter Notebook along with the screenshots to get a better understanding in Python. Jupyter NotebookThe Ju
2 min read
Simple 1D Kernel Density Estimation in Scikit Learn
In this article, we will learn how to use Scikit learn for generating simple 1D kernel density estimation. We will first understand what is kernel density estimation and then we will look into its implementation in Python using KernelDensity class of sklearn.neighbors in scikit learn library. Kernel density estimationA non-parametric method for est
4 min read
Add Julia Kernel to Jupyter
Jupyter Notebook is a popular interactive open-source web application that helps you to create and share documents containing live code, equations, visualizations, and text. Because of its interactive and versatile nature, it has become an indispensable tool for data scientists, engineers, and researchers. It supports various programming languages,
8 min read
How to Fix Kernel Error in Jupyter Notebook
Jupyter Notebook is an open-source framework that comes under Anaconda software. It is a free cloud-based interactive platform used for computing in different types of languages. It is used for data analysis, visualizations, numerical calculations and simulations, equations, executing codes, machine learning, and sharing data easily. So, while perf
15 min read
Creating and updating PowerPoint Presentations in Python using python - pptx
python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won't work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library. Installation: Open the command prompt on your system and write given below command: pip install python-pptx Let's see some of its usag
4 min read
Creating Your Own Python IDE in Python
In this article, we are able to embark on an adventure to create your personal Python Integrated Development Environment (IDE) the usage of Python itself, with the assistance of the PyQt library. What is Python IDE?Python IDEs provide a characteristic-rich environment for coding, debugging, and going for walks in Python packages. While there are ma
3 min read
Creating a Proxy Webserver in Python | Set 2
Prerequisite: Creating a Proxy Webserver in Python - Set1 In this tutorial, a few interesting features are added to make it more useful. Add blacklisting of domains. For Ex. google.com, facebook.com. Create a list of BLACKLIST_DOMAINS in our configuration dict. For now, just ignore/drop the requests received for blacklisted domains. (Ideally, we mu
5 min read
Creating a sorted merged list of two unsorted lists in Python
We need to take two lists in Python and merge them into one. Finally, we display the sorted list. Examples: Input : list1 = [25, 18, 9, 41, 26, 31] list2 = [25, 45, 3, 32, 15, 20] Output : [3, 9, 15, 18, 20, 25, 25, 26, 31, 32, 41, 45] Input : list1 = ["suraj", "anand", "gaurav", "aman", "kishore"] list2 = ["rohan", "ram", "mohan", "priya", "komal"
1 min read
Python | Creating a 3D List
A 3-D List means that we need to make a list that has three parameters to it, i.e., (a x b x c), just like a 3 D array in other languages. In this program we will try to form a 3-D List with its content as "#". Lets look at these following examples: Input : 3 x 3 x 3 Output : [[['#', '#', '#'], ['#', '#', '#'], ['#', '#', '#']], [['#', '#', '#'], [
4 min read
Creating Python Virtual Environment in Windows and Linux
A Virtual Environment is a Python environment, that is an isolated working copy of Python that allows you to work on a specific project without affecting other projects So basically it is a tool that enables multiple side-by-side installations of Python, one for each project. Creating a Python virtual environment in Linux If pip is not in your syst
2 min read
Creating child process using fork() in Python
Create a child process and display process id of both parent and child process. Fork system call use for creates a new process, which is called child process, which runs concurrently with process (which process called system call fork) and this process is called parent process. After a new child process created, both processes will execute the next
2 min read
Python | Creating DataFrame from dict of narray/lists
As we know Pandas is all-time great tools for data analysis. One of the most important data type is dataframe. It is a 2-dimensional labeled data structure with columns of potentially different types. It is generally the most commonly used pandas object. Pandas DataFrame can be created in multiple ways. Let’s discuss how to create Pandas dataframe
2 min read
Python | Catching and Creating Exceptions
Catching all exceptions is sometimes used as a crutch by programmers who can’t remember all of the possible exceptions that might occur in complicated operations. As such, it is also a very good way to write undebuggable code. Because of this, if one catches all exceptions, it is absolutely critical to log or reports the actual reason for the excep
2 min read
Python | Creating a Simple Drawing App in kivy
Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. Kivy Tutorial - Learn Kivy with Examples. Drawing App: In this we are going to create a simple drawing App with th
4 min read
Creating Tabbed Widget With Python-Tkinter
Python offers a range of GUI frameworks that can be used to develop GUI based applications in Python. The most widely used Python interface is Tk interface or tkinter( as renamed in Python 3.x) . The Tkinter module offers a wide range of widgets that can be used to develop GUI applications much faster and easier compared to the other interfaces off
5 min read
Creating NotePad using PyQt5 - Python
In this article we will see how we can create notepad using PyQt5.Notepad is a generic text editor that allows you to create, open, edit, and read plaintext files.PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided
7 min read
Python VLC - Creating MediaPlayer object
In this article we will see how we can create a MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediaPlayer object is the basic object in vlc module for playing the video. MediaPlayer class is the basic
1 min read
Creating nested dataclass objects in Python
Dataclasses is an inbuilt Python module which contains decorators and functions for automatically adding special methods like __init__() and __repr__() to user-defined classes. Dataclass Object is an object built into the Dataclasses module. This function is used as a decorator to add special methods directly to a user-defined class. This decorator
3 min read
Python VLC Instance - Creating MediaListPlayer Instance
In this article we will see how we can create a MediaListPlayer instance from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we
2 min read
Python VLC Instance - Creating Media path
In this article we will see how we can create a media path from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can create me
2 min read
Python VLC Instance - Creating MediaList Instance
In this article we will see how we can create a MediaList Instance from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can c
2 min read
Python VLC Instance - Creating new Media Instance
In this article we will see how we can create a Media instance from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can creat
2 min read
Python VLC Instance - Creating MediaPlayer Instance
In this article we will see how we can create a MediaPlayer instance from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can
2 min read
Creating Decorator inside a class in Python
We can easily create decorators inside a class and it is easily accessible for its child classes. During Decorator creation, we must take care that the function that we are defining inside the decorator must take current object reference (self) as a parameter, and while we are accessing that decorator from child class that time we must call that de
3 min read
Creating Your First Application in Python
Python is one of the simplest programming language out there. In fact, it was developed for the sole purpose of simplifying the process of learning a programming language and exposed beginners to the concepts of Programming. In this article, we will be building a Python Application. Not to worry it won't be anything fancy or complex. But before we
5 min read
Creating Files in HDFS using Python Snakebite
Hadoop is a popular big data framework written in Java. But it is not necessary to use Java for working on Hadoop. Some other programming languages like Python, C++ can also be used. We can write C++ code for Hadoop using pipes API or Hadoop pipes. Hadoop pipes enable task-tracker with the help of sockets. Python can also be used to write code for
3 min read
Creating a radar sweep animation using arcade in Python
The Radar Sweep are used for displays of single level sweeps of radar data, and their display appears in the Main Display window. With the help of arcade module of Python, it is possible to perform a radar sweep animation. Before starting, it is highly recommended to revise concepts of arcade library. To perform a radar sweep animation, follow the
3 min read
Article Tags :
Practice Tags :