Day 9 · A first artificial neuron
Perceptrons, one decision at a time
Follow the weights, bias and threshold of a simple classifier—with checked calculations, readable formulas, Python examples and plots that show how its boundary moves.
Start the worked guide
Understand the scoreSee how features, weights and bias produce a class.
Check every updateFollow the two-point example through three epochs.
See the boundaryConnect the formulas with the manual and Iris plots.
In this lesson
The quick answer
A weighted score becomes a yes-or-no decision
A perceptron is a linear binary classifier: it weights the input features, adds a bias, then applies a threshold to predict class 0 or class 1. Training changes the weights and bias when a correction is needed.
A single perceptron has no hidden layer. Learning this simple unit makes it easier to understand the larger neural networks in later lessons. If you are coming from Day 8’s guide to training updates, focus here on what one classifier does with an example.
A checked reading path
Understand one perceptron before building a network
A perceptron is a linear binary classifier. It multiplies each input by a weight, adds a bias and applies a threshold to choose a class. Training changes the weights and bias when its prediction disagrees with the target. A single perceptron is a useful foundation for neural networks; it is not, by itself, a deep network with multiple learned layers.
Two experiments, not one shared result: the manual code trains on two constructed points with manually assigned labels. The imported scikit-learn code trains on all 150 Iris rows using Setosa-versus-other-species labels. Their data, starting parameters and training order differ. The full original explanations, code, images and calculations remain below, with separate notes identifying those distinctions and one repeated arithmetic error.
1. Separate the score from the predicted class
For two inputs, the score is a straight-line expression. The weights determine how changes in the two features affect that score. The bias changes the threshold’s position independently of the input values. A score is a real number; the predicted class is the result of applying the chosen threshold.
This checked manual example assigns a score of exactly zero to class 1. The binary prediction implementation inspected and tested in scikit-learn 1.8.0 assigns a positive score to its higher class, and zero to its first class, class 0 here. The library’s training update at a zero score also needs separate attention: its perceptron loss can trigger an update on the boundary even when the binary prediction matches the target. None of the six manual training scores below is zero, so these conventions do not change their checked predictions.
2. Update weights and bias from the current mistake
Let t be the true label and ŷ the predicted label, both either 0 or 1. Their difference e is −1, 0 or 1. A positive error increases the weights in the input’s direction; a negative error moves them oppositely. A zero error leaves both weights and bias unchanged.
The bias update is important: omitting it forces a different training procedure. Compute the score and prediction from the current parameters, then apply the same error to the weights and bias. The next row uses the newly updated parameters. This is the conventional mistake-driven perceptron rule, rather than taking a derivative through a hard threshold to minimize mean squared error.
3. Work through the first two rows
Keep the original manual initialization w = [0.01, −0.02], b = 0 and learning rate η = 0.1. Point A is [2.5, 1.5] with target 1; point B is [1.0, 0.5] with target 0. The row order stays A, then B in every epoch. An epoch is a complete pass through these two rows; each row is one prediction-and-possible-update step.
For A, the first score is 0.01 × 2.5 − 0.02 × 1.5 = −0.005. The prediction is 0, so e = 1 − 0 = 1. The weight increment is 0.1 × [2.5, 1.5] = [0.25, 0.15]. Adding that increment gives w = [0.26, 0.13], while the bias becomes 0.1.
Now use those updated parameters for B. Its score is 0.26 × 1.0 + 0.13 × 0.5 + 0.1 = 0.425. The prediction is 1, but the target is 0, so e = −1. Subtract [0.1, 0.05] from the weights and 0.1 from the bias. At the end of the first epoch, w = [0.16, 0.08] and b = 0.
4. Check all three epochs, including the repeated arithmetic
In epoch 2, A has score 0.52 and is already correct. B has score 0.20 and is still wrong, so it triggers one update. The resulting weights are [0.06, 0.03], and the bias is −0.1. The two points are then correctly classified at scores 0.095 and −0.025.
| Epoch / row | Score z | Prediction | Error t − ŷ | Weights after row | Bias after row |
|---|---|---|---|---|---|
| 1 / 1 | -0.005 | 0 | 1 | [0.26, 0.13] | 0.1 |
| 1 / 2 | 0.425 | 1 | -1 | [0.16, 0.08] | 0.0 |
| 2 / 1 | 0.520 | 1 | 0 | [0.16, 0.08] | 0.0 |
| 2 / 2 | 0.200 | 1 | -1 | [0.06, 0.03] | -0.1 |
| 3 / 1 | 0.095 | 1 | 0 | [0.06, 0.03] | -0.1 |
| 3 / 2 | -0.025 | 0 | 0 | [0.06, 0.03] | -0.1 |
Epoch 3 changes nothing because both predictions are correct. The later repeated explanation in the original article writes 0.06 + 0.015 − 0.1 = −0.019. The correct arithmetic is −0.025, as another original section already states. Both values are negative, so this transcription error does not change the class-0 prediction or the final parameters. The preserved original expression is clearly qualified rather than silently removed.
The new boundary figure is computed from these verified endpoint parameters. Epoch 1 predicts both points as class 1. Epoch 2 separates them, and epoch 3 repeats the same line. This is a successful fit to two training labels, not an identified unique or maximum-margin “optimal” boundary.
5. Read the line without dividing by zero
The decision boundary consists of inputs whose score is zero. With two features, nonzero weights define a line; with more features they define a hyperplane. When the second weight is nonzero, rearranging the equation gives the familiar slope-and-intercept form.
For the final manual parameters, 0.06x₁ + 0.03x₂ − 0.1 = 0, so x₂ = −2x₁ + 10/3. A lies on its class-1 side and B on its class-0 side. If w₂ = 0 but w₁ ≠ 0, use the vertical line x₁ = −b/w₁ instead. When both weights are zero, the score is constant; a normal separating line is not defined.
6. Distinguish the constructed labels from Iris species
The manual code loads Iris, but its training call passes the separately constructed two-row array. Neither exact feature pair occurs in the packaged Iris petal-feature rows used in this check. These labels were chosen for a teaching exercise; they are not verified Setosa-versus-other-species labels from that dataset.
The library example uses petal length and width from all 150 actual Iris flowers. It labels the 50 Setosa rows as 1 and the other 100 rows as 0. Its learned boundary therefore answers a different classification question. In this dataset Setosa petal lengths range from 1.0 to 1.9 cm; assigning target 1 to the manual point with length 2.5 should not be read as an actual Iris annotation.
The original detailed handwritten section mentions an imported model in its heading, but its initialization and arithmetic match the manual two-point run. Follow the verified manual trace when checking that section. Do not expect the full-Iris library run to reproduce those same intermediate weights.
7. Understand what the original scikit-learn code actually ran
All three original Python blocks were executed successfully with NumPy 2.3.5, Matplotlib 3.10.8 and scikit-learn 1.8.0. Plotting used a noninteractive backend; each show call saved and closed a figure. The manual calculations matched an independent exact-fraction reference, and the third plotting block reproduced the listed manual endpoint boundaries.
The second block starts the library estimator from its default zero parameters, uses shuffled data, calls fit for its first one-epoch pass and partial_fit for later passes. In this observed environment, all three plotted library states were w = [−0.14, −0.22], b = 0.4. That model classified all 150 training rows correctly. These are observed version-specific results, not a promise that every release produces identical weights.
A single partial_fit call performs an additional epoch. It is not interchangeable with repeatedly starting fresh fits: initialization, shuffling, warm-start behavior and internal state matter. To compare implementations meaningfully, use the same data, initial parameters, order, label encoding, update-at-boundary convention and stopping rule. Record library versions too.
8. Know what convergence proves
Under its standard assumptions, the perceptron convergence theorem gives finite termination on a finite, linearly separable training set. Nonseparable labels can keep producing mistakes, so a practical implementation needs an iteration limit or stopping policy. A single linear perceptron cannot express every pattern; XOR in the original input space is a familiar example.
Finding a separating boundary does not prove good predictions on unseen examples. The two-row exercise has no held-out evaluation, and neither does the original full-Iris run. Evaluate independent data before making accuracy claims. Deeper networks use multiple learned layers and other activations and training methods; understanding this simple classifier prepares you for those later lessons.
Primary sources: scikit-learn’s Perceptron reference describes estimator settings and incremental training; load_iris describes the packaged dataset. Cornell’s perceptron course notes explain the separating hyperplane and the convergence assumptions. The numeric traces, plots and implementation tie check were independently executed for this lesson.
See the calculation
From one update to a decision boundary
These visuals are drawn from the checked update rule and executed experiments. The two-point example and the full Iris experiment have different data and settings.



The complete original lesson
Every original explanation, formula, code example and image
All original wording remains below, including repeated explanations, calculation tables, the three Python examples and eight original images. Separate notes clarify the two datasets and the arithmetic typo without removing the historical material.
Long equations, tables and code scroll within their own regions. Focus a region with the keyboard and use the arrow keys to read across. Open an image to inspect its available full-size version.
Hello
Introduction to Deep Learning and Neural Networks with a Focus on Perceptrons
Deep Learning is a subset of machine learning that uses neural networks with many layers (hence “deep”) to model and understand complex patterns in data. These networks are inspired by the human brain and are particularly powerful for tasks like image and speech recognition.
Neural Networks consist of interconnected layers of nodes, or neurons. Each neuron receives input, processes it, and passes it to the next layer. The simplest form of a neural network is the Perceptron, which is a single-layer neural network used for binary classification tasks.
Perceptron Explained
A Perceptron is a fundamental unit of a neural network, performing binary classification by making predictions based on a linear predictor function. It works by:
Receiving Input: Taking input features .
Weight Multiplication: Multiplying each input by a corresponding weight .
Summation: Summing the weighted inputs and adding a bias term .
Activation Function: Passing the result through an activation function (typically a step function for a perceptron).
The mathematical formula for a perceptron can be written as:
where is the activation function.
Training a Perceptron
Training involves adjusting the weights and bias to minimize classification errors on the training data. This is typically done using algorithms like the Perceptron Learning Algorithm, which updates weights based on the error in predictions.
Mathematical Foundations
Linear Predictor
Purpose: Calculates the weighted sum of inputs and bias, determining the linear combination that will be used for prediction.
Activation Function
where is often a step function:
Purpose: Transforms the linear predictor into a binary output, classifying the input as either 1 or 0.
Weight Update Rule
where with being the learning rate, the target value, and the predicted value.
Purpose: Adjusts the weights to reduce the error in future predictions. This iterative process helps the perceptron learn from the training data.
Iterative Process
Each iteration involves the following steps:
Prediction: Calculate the linear predictor and apply the activation function to obtain the predicted output .
Error Calculation: Determine the difference between the actual target and the predicted output .
Weight Update: Adjust the weights and bias based on the error. This helps in refining the decision boundary that the perceptron uses to classify the input data.
How Perceptron Helps the Algorithm
Learning from Data: The perceptron adjusts its weights based on the input data and corresponding labels, learning to classify the data correctly over iterations.
Updating Weights: The weight update rule ensures that the perceptron corrects its mistakes, moving towards a model that can generalize well to unseen data.
Binary Classification: By using a step function as the activation function, the perceptron can classify inputs into two categories, making it useful for binary classification tasks.
Perception and mathematics behind it is explained below in 3 Practical ways:
Perceptrons form the building blocks for more complex neural networks used in deep learning. Understanding their working and mathematical foundation is crucial for delving into more advanced topics in neural networks and deep learning.
For a detailed exploration and understand math behind it, continue reading our article below.
Perceptron Training

Here are the 3 ways of:
1- Manual Perceptron Training Code (without importing perceptron)
2- Algorithm with Importing Perceptron
3- Mathematics Behind Perceptron (detailed without code)
We showed all these steps to help you gain a deep understanding of perceptrons and the mathematics behind them. Check numbers 1, 2, and 3 below:
1- Manual Perceptron Training Code
Below is the code that performs manual updates and visualizes the decision boundary at each step:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
# Load the Iris dataset
iris = load_iris()
X = iris.data[:, (2, 3)] # Using petal length and petal width as features
y = (iris.target == 0).astype(int) # Binary target: Iris Setosa vs. others
# Initial parameters
weights = np.array([0.01, -0.02])
bias = 0.0
learning_rate = 0.1
# Function to calculate the net input
def net_input(X, weights, bias):
return np.dot(X, weights) + bias
# Function to apply the activation function (step function)
def predict(X, weights, bias):
return np.where(net_input(X, weights, bias) >= 0.0, 1, 0)
# Function to plot the decision boundary
def plot_decision_boundary(weights, bias, X, y, iteration):
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.01),
np.arange(y_min, y_max, 0.01))
Z = predict(np.c_[xx.ravel(), yy.ravel()], weights, bias)
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, alpha=0.3, cmap=plt.cm.Paired)
plt.scatter(X[:, 0], X[:, 1], c=y, edgecolors='k', cmap=plt.cm.Paired)
plt.xlabel("Petal Length (cm)")
plt.ylabel("Petal Width (cm)")
plt.title(f"Decision Boundary after Iteration {iteration}")
plt.show()
# Training loop with detailed logging and plotting
def manual_perceptron_train(X, y, weights, bias, learning_rate, num_iterations):
for iteration in range(num_iterations):
print(f"Iteration {iteration + 1}")
for xi, target in zip(X, y):
z = net_input(xi, weights, bias)
y_hat = predict(xi.reshape(1, -1), weights, bias)[0]
error = target - y_hat
print(f"Data Point: {xi}, True Label: {target}, Net Input: {z}, Predicted: {y_hat}, Error: {error}")
if error != 0:
weights += learning_rate * error * xi
bias += learning_rate * error
print(f"Updated Weights: {weights}, Updated Bias: {bias}")
plot_decision_boundary(weights, bias, X, y, iteration + 1)
print(f"Weights: {weights}, Bias: {bias}")
# Ensure both classes are present in the subset for training
X_train = np.array([[2.5, 1.5], [1.0, 0.5]])
y_train = np.array([1, 0])
# Train the perceptron and plot decision boundaries
manual_perceptron_train(X_train, y_train, weights, bias, learning_rate, 3)
This code demonstrates how the weights and bias are updated at each step based on the perceptron learning rule. The decision boundary is plotted after each iteration to visualize how it evolves as the model learns from the data.
We hope this detailed walkthrough of the perceptron training algorithm and manual implementation helps you understand the inner workings of this fundamental machine learning model.
Results


2- Algorithm with Importing Perceptron
This part demonstrates the Perceptron training using sklearn’s Perceptron class. This approach abstracts the manual weight updates and leverages sklearn’s built-in methods:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.linear_model import Perceptron
# Load the Iris dataset
iris = load_iris()
X = iris.data[:, (2, 3)]
y = (iris.target == 0).astype(int)
# Initialize the Perceptron model
per_clf = Perceptron(max_iter=1, eta0=0.1, random_state=42, tol=None, warm_start=True)
# Function to plot decision boundary
def plot_decision_boundary(model, X, y, iteration):
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.01), np.arange(y_min, y_max, 0.01))
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, alpha=0.3, cmap=plt.cm.Paired)
plt.scatter(X[:, 0], X[:, 1], c=y, edgecolors='k', cmap=plt.cm.Paired)
plt.xlabel("Petal Length (cm)")
plt.ylabel("Petal Width (cm)")
plt.title(f"Perceptron Decision Boundary after Iteration {iteration}")
plt.show()
# Train the perceptron for multiple iterations
def perceptron_train(X, y, model, num_iterations):
for iteration in range(num_iterations):
if iteration == 0:
model.fit(X, y)
else:
model.partial_fit(X, y, classes=np.array([0, 1]))
plot_decision_boundary(model, X, y, iteration + 1)
# Train the perceptron
perceptron_train(X, y, per_clf, 3)
Results:


Mathematic Behind the code Step y Step
3- Mathematic Behind the code with imported Perception
Initial weights:
Initial bias:
Learning rate:
Iteration 1
First Training Instance ([2.5, 1.5]) with Label ( 1 )
Prediction:
Weight Update:
Second Training Instance ([1.0, 0.5]) with Label ( 0 )
Prediction:
Weight Update:
Results after Iteration 1:
| Iteration | Weights | Bias |
|---|---|---|
| 1 | [0.16, 0.08] | 0.0 |
Perceptron Training Part 2
Iteration 2
First Training Instance ([2.5, 1.5]) with Label ( 1 )
Prediction:
Weight Update:
No update since
Second Training Instance ([1.0, 0.5]) with Label ( 0 )
Prediction:
Weight Update:
Results after Iteration 2:
| Iteration | Weights | Bias |
|---|---|---|
| 2 | [0.06, 0.03] | -0.1 |
Perceptron Training Part 3
Iteration 3
First Training Instance ([2.5, 1.5]) with Label ( 1 )
Prediction:
Weight Update:
No update since
Second Training Instance ([1.0, 0.5]) with Label ( 0 )
Prediction:
Weight Update:
No update since
Results after Iteration 3:
| Iteration | Weights | Bias |
|---|---|---|
| 3 | [0.06, 0.03] | -0.1 |
Perceptron Training Part 4
Summary and Final Results
The Perceptron has undergone three iterations. Below are the weights and bias at each iteration:
| Iteration | Weights () | Bias () |
|---|---|---|
| 1 | ||
| 2 | ||
| 3 |
Now lets Visualise the table:
import numpy as np
import matplotlib.pyplot as plt
# Define the weights and biases from the table
iterations = [1, 2, 3]
weights = np.array([[0.16, 0.08], [0.06, 0.03], [0.06, 0.03]])
biases = [0.0, -0.1, -0.1]
# Define the training data
X_train = np.array([[2.5, 1.5], [1.0, 0.5]])
y_train = np.array([1, 0])
# Function to plot the decision boundary for a given iteration
def plot_decision_boundary(weights, bias, X_train, y_train, iteration):
x_min, x_max = X_train[:, 0].min() - 1, X_train[:, 0].max() + 1
y_min, y_max = X_train[:, 1].min() - 1, X_train[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.01), np.arange(y_min, y_max, 0.01))
Z = np.dot(np.c_[xx.ravel(), yy.ravel()], weights) + bias
Z = np.where(Z >= 0, 1, 0).reshape(xx.shape)
plt.contourf(xx, yy, Z, alpha=0.3, cmap=plt.cm.Paired)
plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train, edgecolors='k', cmap=plt.cm.Paired)
plt.xlabel("Petal Length (cm)")
plt.ylabel("Petal Width (cm)")
plt.title(f"Decision Boundary after Iteration {iteration}")
plt.show()
# Plot the decision boundary for each iteration
for i in range(len(iterations)):
plot_decision_boundary(weights[i], biases[i], X_train, y_train, iterations[i])
Here is the result of drawing it :



You May Still Wonder, How Decision Boundary Is Drawn?
The only question you might have is how it knows how to draw the decision boundary line to separate data.
Understanding the Decision Boundary in Perceptron Learning
Understanding the Decision Boundary in Perceptron Learning
Here, we’ll explore how a perceptron learnt in our models above to classify data by adjusting its decision boundary through iterations.
Concepts to Understand
Decision Boundary: This is the line (or hyperplane in higher dimensions) where the perceptron classifier decides between two classes. It’s defined as:
where is the weight vector, is the feature vector, and is the bias term.
Learning Process: The perceptron adjusts and to minimize errors by updating them based on the classification results.
Decision Boundary After Iteration 1:
Equation:
Rearranged:
Iteration 2
For :
Net Input Calculation:
Prediction: Since is greater than 0, the perceptron predicts class 1.
Actual Label: 1 (No Error)
For :
Net Input Calculation:
Prediction: Since is greater than 0, the perceptron predicts class 1.
Actual Label: 0 (Error = 0 – 1 = -1)
Update Weights and Bias:
Decision Boundary After Iteration 2:
Equation:
Rearranged:
Iteration 3
For :
Net Input Calculation:
Prediction: Since is greater than 0, the perceptron predicts class 1.
Actual Label: 1 (No Error)
For :
Net Input Calculation:
Prediction: Since is less than 0, the perceptron predicts class 0.
Actual Label: 0 (No Error)
Decision Boundary After Iteration 3:
Equation:
Rearranged:
Conclusion
As we can see from the iterations, the perceptron adjusts its weights and bias to better fit the data. The decision boundary evolves through these adjustments:
Iteration 1: Adjusts based on the errors from both data points, resulting in a boundary that may not perfectly separate the classes.
Iteration 2: Further adjustments refine the boundary, moving closer to an optimal separation.
Iteration 3: Shows that the decision boundary has stabilized with correct classifications for the given data points.
The decision boundary is defined by the equation . In this case, it separates the two classes (Iris Setosa vs. others) by adjusting weights and bias based on errors from the training data.
Common questions
Perceptrons, explained clearly
What is a perceptron?
A perceptron is a linear binary classifier. It multiplies input features by weights, adds a bias and applies a threshold to assign a class. A single perceptron has no hidden layer; it is a useful starting point for understanding neural networks.
How do the weights and bias learn?
In the manual example, compute the score and predicted class first. If the prediction differs from the target, add the learning rate times the error times each feature to its weight, and add the learning rate times the error to the bias. Correct predictions leave both unchanged.
How is the decision boundary drawn?
The boundary consists of inputs whose weighted score plus bias equals zero. With two features and a nonzero second weight, rearrange this equation to draw a line. If the second weight is zero, the boundary may be vertical; do not divide by zero.
Are the manual example and the Iris example the same experiment?
No. The manual code trains on two explicitly chosen points with illustrative labels. The scikit-learn example trains on all 150 Iris rows using a Setosa-versus-other-species target, different initialization and shuffled training. Their weights and plots should not be compared as identical runs.
Does a perceptron score represent a probability?
No. The weighted score determines which side of the decision boundary an input occupies. It is not a calibrated probability. This lesson uses a threshold to return class 0 or class 1.
Will a perceptron always converge and generalize?
No. The classical finite-convergence guarantee requires linearly separable training data and the theorem’s assumptions. A single linear boundary cannot solve the standard XOR pattern in its original two input features. Correctly classifying the training points does not establish performance on unseen data.
Continue the series
Next: connect neurons into a network
You have followed a single linear classifier. Day 10 introduces multilayer perceptrons and explains how their outputs change for regression and classification.
Continue to Day 10: regression and classification with MLPs →
Editorial note: the original Python examples were executed in a recorded environment, and the two-point update trace was independently checked. The new charts are computed from those experiments. Training predictions do not establish unseen-data accuracy. The original lesson is preserved in full, with separate clarification notes.
