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:

https://towardsdatascience.com/support-vector-machine-introduction-to-machine-learning-algorithms-934a444fca47

Implementation

import numpy as np class SVM: def __init__(self, learning_rate=0.001, lambda_param=0.01, n_iters=1000): self.lr = 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] * (np.dot(x_i, self.w) - self.b) >= 1 if condition: self.w -= self.lr * (2 * self.lambda_param * self.w) else: self.w -= self.lr * (2 * self.lambda_param * self.w - np.dot(x_i, y_[idx])) self.b -= self.lr * y_[idx] def predict(self, X): approx = np.dot(X, self.w) - self.b return np.sign(approx)