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.
import numpy as np class Perceptron: def __init__(self, learning_rate=0.01, n_iters=1000): self.lr = 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 = np.dot(x_i, self.weights) + self.bias y_predicted = self.activation_func(linear_output) # Perceptron update rule update = self.lr * (y_[idx] - y_predicted) self.weights += update * x_i self.bias += update def predict(self, X): linear_output = np.dot(X, 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)
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.