Python Engineer

Free Python and Machine Learning Tutorials

Become A Patron and get exclusive content! Get access to ML From Scratch notebooks, join a private Slack channel, get priority response, and more! I really appreciate the support!

back to course overview

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

19 Nov 2019

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) else: 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)