Back to course overview

Perceptron in Python - ML From Scratch 06

In this Machine Learning from Scratch Tutorial, we are going to implement a single-layer Perceptron 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 Perceptron: def __init__(self, learning_rate=0.01, n_iters=1000): = learning_rate self.n_iters = n_iters self.activation_func = self._unit_step_func self.weights = None self.bias = None def fit(self, X, y): n_samples, n_features = X.shape # init parameters self.weights = np.zeros(n_features) self.bias = 0 y_ = np.array([1 if i > 0 else 0 for i in y]) for _ in range(self.n_iters): for idx, x_i in enumerate(X): linear_output =, self.weights) + self.bias y_predicted = self.activation_func(linear_output) # Perceptron update rule update = * (y_[idx] - y_predicted) self.weights += update * x_i self.bias += update def predict(self, X): linear_output =, self.weights) + self.bias y_predicted = self.activation_func(linear_output) return y_predicted def _unit_step_func(self, x): return np.where(x>=0, 1, 0)

FREE VS Code / PyCharm Extensions I Use

🪁 Code faster with Kite, AI-powered autocomplete: Link *

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link *

* These are affiliate links. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you! 🙏

Check out my Courses