Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Data Science
  • Data Science Projects
  • Data Analysis
  • Data Visualization
  • Machine Learning
  • ML Projects
  • Deep Learning
  • NLP
  • Computer Vision
  • Artificial Intelligence
Open In App
Next Article:
Linear Mapping
Next article icon

Non-Linear SVM - ML

Last Updated : 19 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Support Vector Machines (SVM) are algorithms for classification and regression tasks. However, the standard (linear) SVM can only classify data that is linearly separable, meaning the classes can be separated by a straight line (in 2D) or a hyperplane (in higher dimensions). Non-Linear SVM extends SVM to handle complex, non-linearly separable data using kernels. Kernels enable SVM to work in higher dimensions where data can become linearly separable.

Why Non-Linear SVM is Required

In many situations data cannot be separated with a straight line. For example, one group of points might surround another group in a circle. A simple Support Vector Machines (SVM) won't work well here because it only draws straight lines. Non-linear SVM is needed because it can draw curved lines to separate such data properly. This helps the model make better predictions when the data has complex shapes or patterns. SVM uses a technique called the kernel trick.

svm
Linear vs Non-Linear SVM

Non-Linear SVM uses kernels to work in higher dimensions where data can become linearly separable.

What is Kernel?

Instead of explicitly computing the transformation the kernel computes the dot product of data points in the higher-dimensional space directly that helps a model find patterns in complex data and transforming the data into a higher-dimensional space where it becomes easier to separate different classes or detect relationships.

For example, suppose we have data points shaped like two concentric circles: one circle represents one class and the other circle represents another class. If we try to separate these classes with a straight line it can't be done because the data is not linearly separable in its current form.

When we use a kernel function it transforms the original 2D data like the concentric circles into a higher-dimensional space where the data becomes linearly separable. In that higher-dimensional space the SVM finds a simple straight-line decision boundary to separate the classes.

When we bring this straight-line decision boundary back to the original 2D space it no longer looks like a straight line. Instead, it appears as a circular boundary that perfectly separates the two classes. This happens because the kernel trick allows the SVM to "see" the data in a new way enabling it to draw a boundary that fits the original shape of the data.

Popular kernel functions in SVM

  • Radial Basis Function (RBF): Captures patterns in data by measuring the distance between points and is ideal for circular or spherical relationships.
  • Linear Kernel: Works for data that is linearly separable problem without complex transformations.
  • Polynomial Kernel: Models more complex relationships using polynomial equations.
  • Sigmoid Kernel: Mimics neural network behavior using sigmoid function and is suitable for specific non-linear problems.

Below are some examples of Non-Linear SVM Classification.

Example 1: Non linear SVM in Circular Decision Boundary

Below is the Python implementation for Non linear SVM in circular decision boundary.

1. Importing Libraries

We begin by importing the necessary libraries for data generation, model training, evaluation, and visualization.

Python
import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_circles from sklearn.svm import SVC from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score 

2. Creating and Splitting the Dataset

We generate a synthetic dataset of concentric circles and split it into training and testing sets.

Python
X, y = make_circles(n_samples=500, factor=0.5, noise=0.05, random_state=42) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) 

3. Creating and Training the Non-Linear SVM Model

We create an SVM classifier using the RBF kernel to handle non-linear patterns and train it on the data.

Python
svm = SVC(kernel='rbf', C=1, gamma=0.5)  # RBF kernel allows learning circular boundaries svm.fit(X_train, y_train) 

4. Making Predictions and Evaluating the Model

We predict the labels for the test set and compute the accuracy of the model.

Python
y_pred = svm.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print(f"Accuracy: {accuracy:.2f}") 

5. Visualizing the Decision Boundary

We define a function to visualize the decision boundary of the trained non-linear SVM on the dataset.

Python
def plot_decision_boundary(X, y, model):     x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1     y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1     xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.01),                          np.arange(y_min, y_max, 0.01))          Z = model.predict(np.c_[xx.ravel(), yy.ravel()])     Z = Z.reshape(xx.shape)          plt.contourf(xx, yy, Z, alpha=0.8, cmap=plt.cm.Paired)     plt.scatter(X[:, 0], X[:, 1], c=y, edgecolor='k', cmap=plt.cm.Paired)     plt.title("Non-linear SVM with RBF Kernel")     plt.show()  # Plot the decision boundary plot_decision_boundary(X, y, svm) 

Output:

non_linear_svm_rbf_kernel
Non Linear SVM with RBF kernel

Non linear SVM provided a decision boundary where the SVM successfully separates the two circular classes (inner and outer circles) using a curved boundary with help of RBF kernel.

Example 2: Non linear SVM for Radial Curve Pattern

Now we will see how different kernel works. We will be using polynomial kernel function for dataset with radial curve pattern.

1. Importing Libraries

We import essential libraries for dataset creation, SVM modeling, evaluation, and visualization.

Python
import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_moons from sklearn.svm import SVC from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score 

2. Creating and Splitting the Dataset

We generate a synthetic "two moons" dataset, which is non-linearly separable, and split it into training and test sets.

Python
X, y = make_moons(n_samples=500, noise=0.1, random_state=42) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) 

3. Creating and Training the SVM with Polynomial Kernel

We build an SVM classifier with a polynomial kernel and train it on the training data.

Python
svm_poly = SVC(kernel='poly', degree=3, C=1, coef0=1)  # degree and coef0 control the curve of the boundary svm_poly.fit(X_train, y_train) 

4. Making Predictions and Evaluating the Model

We use the trained model to predict test labels and evaluate its accuracy.

Python
y_pred = svm_poly.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print(f"Accuracy: {accuracy:.2f}") 

5. Visualizing the Decision Boundary

We define a function to plot the decision boundary learned by the SVM with a polynomial kernel.

Python
def plot_decision_boundary(X, y, model):     x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1     y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1     xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.01),                          np.arange(y_min, y_max, 0.01))          Z = model.predict(np.c_[xx.ravel(), yy.ravel()])     Z = Z.reshape(xx.shape)          plt.contourf(xx, yy, Z, alpha=0.8, cmap=plt.cm.Paired)     plt.scatter(X[:, 0], X[:, 1], c=y, edgecolor='k', cmap=plt.cm.Paired)     plt.title("Non-linear SVM with Polynomial Kernel")     plt.show()      plot_decision_boundary(X, y, svm_poly) 

Output:

non_linear_svm_polynomial_kernel
Non linear SVM with Polynomial Kernel

Polynomial kernel creates a smooth, non-linear decision boundary that effectively separates the two curved regions.

Linear SVM vs Non-Linear SVM

Feature

Linear SVM

Non-Linear SVM

Decision Boundary

Straight line or hyperplane

Curved or complex boundaries

Data Separation

Works well when data is linearly separable

Suitable for non-linearly separable data

Kernel Usage

No kernel or uses a linear kernel

Uses non-linear kernels (e.g., RBF, polynomial)

Computational Cost

Generally faster and less complex

More computationally intensive

Example Use Case

Spam detection with simple features

Image classification or handwriting recognition

Applications

  1. Image Classification: They are widely used for image recognition tasks such as handwritten digit recognition like MNIST dataset, where the data classes are not linearly separable.
  2. Bioinformatics: Used in gene expression analysis and protein classification where the relationships between variables are complex and non-linear.
  3. Natural Language Processing (NLP): Used for text classification tasks like spam filtering or sentiment analysis where non-linear relationships exist between words and sentiments.
  4. Medical Diagnosis: Effective for classifying diseases based on patient data such as tumor classification where data have non-linear patterns.
  5. Fraud Detection: They can identify fraudulent activities by detecting unusual patterns in transactional data.
  6. Voice and Speech Recognition: Useful for separating different voice signals or identifying speech patterns where non-linear decision boundaries are needed.

Next Article
Linear Mapping

P

Praveen Sinha
Improve
Article Tags :
  • Machine Learning
  • AI-ML-DS
  • AI-ML-DS With Python
Practice Tags :
  • Machine Learning

Similar Reads

    ML | Non-Linear SVM
    Support Vector Machines (SVM) are algorithms for classification and regression tasks. However, the standard (linear) SVM can only classify data that is linearly separable, meaning the classes can be separated by a straight line (in 2D) or a hyperplane (in higher dimensions). Non-Linear SVM extends S
    6 min read
    Linear Mapping
    Linear mapping is a mathematical operation that transforms a set of input values into a set of output values using a linear function. In machine learning, linear mapping is often used as a preprocessing step to transform the input data into a more suitable format for analysis. Linear mapping can als
    7 min read
    SVM vs KNN in Machine Learning
    Support Vector Machine(SVM) and K Nearest Neighbours(KNN) both are very popular supervised machine learning algorithms used for classification and regression purpose. Both SVM and KNN play an important role in Supervised Learning.Table of Content Support Vector Machine(SVM)K Nearest Neighbour(KNN)Su
    4 min read
    PCA and SVM Pipeline in Python
    Principal Component Analysis (PCA) and Support Vector Machines (SVM) are powerful techniques used in machine learning for dimensionality reduction and classification, respectively. Combining them into a pipeline can enhance the performance of the overall system, especially when dealing with high-dim
    5 min read
    Polynomial Regression for Non-Linear Data - ML
    Non-linear data is usually encountered in daily life. Consider some of the equations of motion as studied in physics. Projectile Motion: The height of a projectile is calculated as h = -½ gt2 +ut +ho Equation of motion under free fall: The distance travelled by an object after falling freely under g
    5 min read
    Separating Hyperplanes in SVM
    Support Vector Machine is the supervised machine learning algorithm, that is used in both classification and regression of models. The idea behind it is simple to just find a plane or a boundary that separates the data between two classes. Support Vectors: Support vectors are the data points that ar
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences