back to course overview
SVM (Support Vector Machine) in Python - ML From Scratch 07
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.
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)
Join My Newsletter! Get Python and ML tips emailed directly to your inbox. Each month you’ll get a summary of all the content I created, including the newest videos, articles, promotions, tips, and more.
Learn all the necessary basics to get started with TensorFlow 2 and Keras.
Learn all the necessary basics to get started with this deep learning framework.
Implement popular Machine Learning algorithms from scratch using only built-in Python modules and numpy.