Skip to content

SVM (Support Vector Machine) in Python - ML From Scratch 07

Implement a SVM (Support Vector Machine) algorithm using only built-in Python, and learn about the math behind this popular ML algorithm. modules and numpy

In this Machine Learning from Scratch Tutorial, we are going to implement a SVM (Support Vector Machine) algorithm using only built-in Python modules and numpy. We will also learn about the concept and the math behind this popular ML algorithm.

All algorithms from this course can be found on GitHub together with example tests.

Further readings:


import numpy as np 

class SVM:

    def __init__(self, learning_rate=0.001, lambda_param=0.01, n_iters=1000): = learning_rate
        self.lambda_param = lambda_param
        self.n_iters = n_iters
        self.w = None
        self.b = None

    def fit(self, X, y):
        n_samples, n_features = X.shape

        y_ = np.where(y <= 0, -1, 1)

        self.w = np.zeros(n_features)
        self.b = 0

        for _ in range(self.n_iters):
            for idx, x_i in enumerate(X):
                condition = y_[idx] * (, self.w) - self.b) >= 1
                if condition:
                    self.w -= * (2 * self.lambda_param * self.w)
                    self.w -= * (2 * self.lambda_param * self.w -, y_[idx]))
                    self.b -= * y_[idx]

    def predict(self, X):
        approx =, self.w) - self.b
        return np.sign(approx)

FREE VS Code / PyCharm Extensions I Use

鉁 Write cleaner code with Sourcery, instant refactoring suggestions: Link*

PySaaS: The Pure Python SaaS Starter Kit

馃殌 Build a software business faster with pure Python: Link*

* These are affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 馃檹