Machine Learning – Tutorial 25

Beginning SVM from Scratch in Python

import matplotlib.pyplot as plt
from matplotlib import style
import numpy as np

# build SVM class

class Support_Vector_Machine:
    # The __init__ method of a class is one that runs whenever an object is created with the class
    # calling self in the class allows sharing of variables across the class, so is included in all function defs
    def __init__(self, visualisation=True):
        # sets visualisations to what ever the user specifies (defaults to True)
        self.visualisation = visualisation
        # defines colours for the two states 1 & -1
        self.colors = {1:'r', -1:'b'}
        # sets some standards for the graphs
        if self.visualisation:
            self.fig = plt.figure()
   = self.fig.add_subplot(1,1,1)
    # train
    def fit(self, data):

    def predict(self,features):
        # sign( x.w+b )
        classification = np.sign(,self.w)+self.b)

        return classification

# define data dictionary
data_dict = {-1:np.array([[1,7],


Leave a Reply