Galle, LK--:--5/6 sites live

Implementing SVM Classifier from Scratch in Python

Margin-maximizing theory එක, වැඩ කරන code එකකට හරවනවා මේකෙන් — algorithm එක ඇත්තටම step එකෙන් step එක ඒ optimal boundary එක හොයනවා ඔයාට පේනවා.

This turns the margin-maximizing theory into working code — you'll see the algorithm actually search for that optimal boundary step by step.

14 May 20266 min readSelf Guide · Stage 15#Building Models from Scratch#Algorithms from Scratch#Machine learning

Lesson 39 of 64 · Part 3 · Building Models from Scratch · Algorithms from Scratch · bilingual notes (English + සිංහල)

Why this matters. This turns the margin-maximizing theory into working code — you'll see the algorithm actually search for that optimal boundary step by step.

සිංහලෙන්: Margin-maximizing theory එක, වැඩ කරන code එකකට හරවනවා මේකෙන් — algorithm එක ඇත්තටම step එකෙන් step එක ඒ optimal boundary එක හොයනවා ඔයාට පේනවා.

What you'll use this for. Once implemented, you'll compare its accuracy directly to Logistic Regression on the same data — a useful, concrete way to see how different algorithms handle the exact same problem.

සිංහලෙන්: Implement කරලා ඉවර උනාට පස්සෙ, එකම data එකට Logistic Regression එකේ accuracy එකට direct ව compare කරනවා — algorithms වෙනස් ඒවා එකම problem එකක් handle කරන්නෙ කොහොමද කියලා දකින්න පුළුවන් concrete විදිහක් තමයි ඒක.

Key principles

  • A hyperparameter like C controls a trade-off, not a fixed rule. A small C allows a wider margin but tolerates some misclassified points; a large C forces stricter separation but risks overfitting — there's no single correct value, only a trade-off to tune.
    C වගේ hyperparameter එකකින් control වෙන්නෙ trade-off එකක්, fixed rule එකක් නෙවෙයි

Walkthrough

SVM Classifier

Equation of the Hyperplane:

y = wx - b

Gradient Descent:

Gradient Descent is an optimization algorithm used for minimizing the loss function in various machine learning algorithms. It is used for updating the parameters of the learning model.

w = w - α*dw

b = b - α*db

Learning Rate:

Learning rate is a tuning parameter in an optimization algorithm that determines the step size at each iteration while moving toward a minimum of a loss function.

Importing the Dependencies

ExamplePython
# importing numpy library
import numpy as np

Support Vector Machine Classifier

ExamplePython
class SVM_classifier():

  # initiating the hyperparameters
  def __init__(self, learning_rate, no_of_iterations, lambda_parameter):

    self.learning_rate = learning_rate
    self.no_of_iterations = no_of_iterations
    self.lambda_parameter = lambda_parameter

  
  # fitting the dataset to SVM Classifier
  def fit(self, X, Y):

    # m  --> number of Data points --> number of rows
    # n  --> number of input features --> number of columns
    self.m, self.n = X.shape

    # initiating the weight value and bias value

    self.w = np.zeros(self.n)

    self.b = 0

    self.X = X

    self.Y = Y

    # implementing Gradient Descent algorithm for Optimization

    for i in range(self.no_of_iterations):
      self.update_weights()

  # function for updating the weight and bias value
  def update_weights(self):

    # label encoding
    y_label = np.where(self.Y <= 0, -1, 1)

    # gradients ( dw, db)
    for index, x_i in enumerate(self.X):

      condition = y_label[index] * (np.dot(x_i, self.w) - self.b) >= 1

      if (condition == True):

        dw = 2 * self.lambda_parameter * self.w
        db = 0

      else:

        dw = 2 * self.lambda_parameter * self.w - np.dot(x_i, y_label[index])
        db = y_label[index]

      self.w = self.w - self.learning_rate * dw

      self.b = self.b - self.learning_rate * db

  # predict the label for a given input value
  def predict(self, X):

    output = np.dot(X, self.w) - self.b
    
    predicted_labels = np.sign(output)

    y_hat = np.where(predicted_labels <= -1, 0, 1)

    return y_hat

Importing the Dependencies

ExamplePython
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

Data Collection & Processing

ExamplePython
# loading the data from csv file to pandas dataframe
diabetes_data = pd.read_csv('/content/diabetes.csv')
ExamplePython
# print the first 5 rows of the dataframe
diabetes_data.head()
PregnanciesGlucoseBloodPressureSkinThicknessInsulinBMIDiabetesPedigreeFunction…
061487235033.60.627…
11856629026.60.351…
28183640023.30.672…
318966239428.10.167…
40137403516843.12.288…
ExamplePython
# number of rows and columns in the dataset
diabetes_data.shape

Output

Output
(768, 9)
ExamplePython
# getting the statistical measures of the dataset
diabetes_data.describe()
PregnanciesGlucoseBloodPressureSkinThicknessInsulinBMIDiabetesPedigreeFunction…
count768.000000768.000000768.000000768.000000768.000000768.000000768.000000…
mean3.845052120.89453169.10546920.53645879.79947931.9925780.471876…
std3.36957831.97261819.35580715.952218115.2440027.8841600.331329…
min0.0000000.0000000.0000000.0000000.0000000.0000000.078000…
25%1.00000099.00000062.0000000.0000000.00000027.3000000.243750…
50%3.000000117.00000072.00000023.00000030.50000032.0000000.372500…

… 2 more rows

ExamplePython
diabetes_data['Outcome'].value_counts()

Output

Output
0    500
1    268
Name: Outcome, dtype: int64

0 --> Non-diabetic

1 --> Diabetic

ExamplePython
# separating the features and target

features = diabetes_data.drop(columns='Outcome', axis=1)

target = diabetes_data['Outcome']
ExamplePython
print(features)

Output

Output
     Pregnancies  Glucose  BloodPressure  ...   BMI  DiabetesPedigreeFunction  Age
0              6      148             72  ...  33.6                     0.627   50
1              1       85             66  ...  26.6                     0.351   31
2              8      183             64  ...  23.3                     0.672   32
3              1       89             66  ...  28.1                     0.167   21
4              0      137             40  ...  43.1                     2.288   33
..           ...      ...            ...  ...   ...                       ...  ...
763           10      101             76  ...  32.9                     0.171   63
764            2      122             70  ...  36.8                     0.340   27
765            5      121             72  ...  26.2                     0.245   30
766            1      126             60  ...  30.1                     0.349   47
767            1       93             70  ...  30.4                     0.315   23

[768 rows x 8 columns]
ExamplePython
print(target)

Output

Output
0      1
1      0
2      1
3      0
4      1
      ..
763    0
764    0
765    0
766    1
767    0
Name: Outcome, Length: 768, dtype: int64

Data Standardization

ExamplePython
scaler = StandardScaler()
ExamplePython
scaler.fit(features)

Output

Output
StandardScaler(copy=True, with_mean=True, with_std=True)
ExamplePython
standardized_data = scaler.transform(features)
ExamplePython
print(standardized_data)

Output

Output
[[ 0.63994726  0.84832379  0.14964075 ...  0.20401277  0.46849198
   1.4259954 ]
 [-0.84488505 -1.12339636 -0.16054575 ... -0.68442195 -0.36506078
  -0.19067191]
 [ 1.23388019  1.94372388 -0.26394125 ... -1.10325546  0.60439732
  -0.10558415]
 ...
 [ 0.3429808   0.00330087  0.14964075 ... -0.73518964 -0.68519336
  -0.27575966]
 [-0.84488505  0.1597866  -0.47073225 ... -0.24020459 -0.37110101
   1.17073215]
 [-0.84488505 -0.8730192   0.04624525 ... -0.20212881 -0.47378505
  -0.87137393]]
ExamplePython
features = standardized_data
target = diabetes_data['Outcome']
ExamplePython
print(features)
print(target)

Output

Output
[[ 0.63994726  0.84832379  0.14964075 ...  0.20401277  0.46849198
   1.4259954 ]
 [-0.84488505 -1.12339636 -0.16054575 ... -0.68442195 -0.36506078
  -0.19067191]
 [ 1.23388019  1.94372388 -0.26394125 ... -1.10325546  0.60439732
  -0.10558415]
 ...
 [ 0.3429808   0.00330087  0.14964075 ... -0.73518964 -0.68519336
  -0.27575966]
 [-0.84488505  0.1597866  -0.47073225 ... -0.24020459 -0.37110101
   1.17073215]
 [-0.84488505 -0.8730192   0.04624525 ... -0.20212881 -0.47378505
  -0.87137393]]
0      1
1      0
2      1
3      0
4      1
… (7 more lines)

Train Test Split

ExamplePython
X_train, X_test, Y_train, Y_test = train_test_split(features, target, test_size=0.2, random_state = 2)
ExamplePython
print(features.shape, X_train.shape, X_test.shape)

Output

Output
(768, 8) (614, 8) (154, 8)

Training the Model

Support Vector Machine Classifier

ExamplePython
classifier = SVM_classifier(learning_rate=0.001, no_of_iterations=1000, lambda_parameter=0.01)
ExamplePython
# training the SVM classifier with training data
classifier.fit(X_train, Y_train)

Model Evaluation

Accuracy Score

ExamplePython
# accuracy on training data
X_train_prediction = classifier.predict(X_train)
training_data_accuracy = accuracy_score(Y_train, X_train_prediction)
ExamplePython
print('Accuracy score on training data = ', training_data_accuracy)

Output

Output
Accuracy score on training data =  0.7768729641693811
ExamplePython
# accuracy on training data
X_test_prediction = classifier.predict(X_test)
test_data_accuracy = accuracy_score(Y_test, X_test_prediction)
ExamplePython
print('Accuracy score on test data = ', test_data_accuracy)

Output

Output
Accuracy score on test data =  0.7532467532467533

Building a Predictive System

ExamplePython
input_data = (5,166,72,19,175,25.8,0.587,51)

# change the input data to numpy array
input_data_as_numpy_array = np.asarray(input_data)

# reshape the array
input_data_reshaped = input_data_as_numpy_array.reshape(1,-1)

# standardizing the input data
std_data = scaler.transform(input_data_reshaped)
print(std_data)

prediction = classifier.predict(std_data)
print(prediction)

if (prediction[0] == 0):
  print('The person is not diabetic')

else:
  print('The Person is diabetic')

Output

Output
[[ 0.3429808   1.41167241  0.14964075 -0.09637905  0.82661621 -0.78595734
   0.34768723  1.51108316]]
[1]
The Person is diabetic

Keep going: ← Lesson 38 · Lesson 40 → · Track it in the Self Guide