The Wayback Machine - https://web.archive.org/web/20250404202759/https://www.geeksforgeeks.org/ml-non-linear-svm/
Open In App

ML | Non-Linear SVM

Last Updated : 22 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Support Vector Machines (SVM) are powerful 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.

Understanding Non-Linear SVM

Nonlinear SVM was introduced when the data cannot be separated by a linear decision boundary in the original feature space. The kernel function computes the similarity between data points allowing SVM to capture complex patterns and nonlinear relationships between features. This enables nonlinear SVM to form curved or circular decision boundaries with help of kernel.

What is Kernel Trick?

Instead of explicitly computing the transformation, the kernel trick 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, imagine 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.

non-linear-svm

Non-Linear SVM

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.

Example :  Non-Linear SVM Classification

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

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

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)

# Create and train the non-linear SVM with an RBF kernel
svm = SVC(kernel='rbf', C=1, gamma=0.5)  # C and gamma are hyperparameters
svm.fit(X_train, y_train)

y_pred = svm.predict(X_test)

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

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_decision_boundary(X, y, svm)

Output:

download4

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.

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

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

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)

# Create and train the SVM with a Polynomial kernel
svm_poly = SVC(kernel='poly', degree=3, C=1, coef0=1)  # degree and coef0 are key hyperparameters
svm_poly.fit(X_train, y_train)

y_pred = svm_poly.predict(X_test)

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

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:

download5

Non linear SVM with Polynomial Kernel

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

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.
  7. Customer Segmentation: Helps in customer segments with non-linear patterns in purchasing behavior.

Non-Linear SVM is a versatile and powerful machine learning algorithm that excels in handling complex datasets where linear separation is not possible. By using kernel functions such as RBF, polynomial and sigmoid it transforms data into higher-dimensional spaces to form decision boundaries.



Next Article

Similar Reads

three90RightbarBannerImg