The Perceptron
Neural networks power image recognition, translation and chatbots. Their basic building block is surprisingly simple, and it is one of the oldest ideas in machine learning: the perceptron, proposed by Frank Rosenblatt in 1958. In this lesson you'll build one from scratch with NumPy.
An artificial neuron
A perceptron takes some inputs, multiplies each by a weight, adds a bias, and passes the sum through an activation function. The original perceptron uses a step function: output 1 if the sum is positive, otherwise 0.
z = w1*x1 + w2*x2 + ... + b
output = 1 if z > 0 else 0Geometrically, z = 0 is a straight line (a plane in more dimensions): the perceptron is a linear classifier, just like logistic regression.
import numpy as np
def neuron(x, w, b):
z = np.dot(w, x) + b
return int(z > 0)
# hand-picked weights that implement logical AND
w, b = np.array([1.0, 1.0]), -1.5
for x in [(0, 0), (0, 1), (1, 0), (1, 1)]:
print(x, "->", neuron(np.array(x), w, b))(0, 0) -> 0
(0, 1) -> 0
(1, 0) -> 0
(1, 1) -> 1
With the right weights, one neuron computes logical AND. The interesting part is learning those weights from examples.
The perceptron learning rule
Start with zero weights. For every training example:
- Predict with the current weights.
- If the prediction is wrong, nudge the weights towards the right answer:
w += lr * (target - prediction) * xandb += lr * (target - prediction). - Correct predictions change nothing.
Repeat over the data set (each pass is an epoch) until there are no mistakes.
import numpy as np
def train_perceptron(X, y, lr=0.1, epochs=20):
w = np.zeros(X.shape[1])
b = 0.0
for epoch in range(1, epochs + 1):
errors = 0
for xi, target in zip(X, y):
pred = int(np.dot(w, xi) + b > 0)
update = lr * (target - pred)
w += update * xi
b += update
errors += int(update != 0)
print(f"epoch {epoch}: errors={errors} w={w.round(2)} b={b:.2f}")
if errors == 0:
break
return w, b
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
y_or = np.array([0, 1, 1, 1])
w, b = train_perceptron(X, y_or)
print("learned OR:", [int(np.dot(w, x) + b > 0) for x in X])epoch 1: errors=1 w=[0. 0.1] b=0.10
epoch 2: errors=2 w=[0.1 0.1] b=0.10
epoch 3: errors=1 w=[0.1 0.1] b=0.00
epoch 4: errors=0 w=[0.1 0.1] b=0.00
learned OR: [0, 1, 1, 1]
After a few epochs the perceptron has learned OR on its own. The perceptron convergence theorem guarantees this: if a straight line can separate the classes, the rule will find one.
A real data set
Let's train our perceptron on two well-separated groups of points and draw the line it learns:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
X, y = make_blobs(n_samples=100, centers=[[-2, -2], [2, 2]], cluster_std=1.0, random_state=1)
w, b = np.zeros(2), 0.0
for epoch in range(30):
mistakes = 0
for xi, target in zip(X, y):
pred = int(np.dot(w, xi) + b > 0)
w += 0.1 * (target - pred) * xi
b += 0.1 * (target - pred)
mistakes += int(pred != target)
if mistakes == 0:
break
accuracy = np.mean((X @ w + b > 0).astype(int) == y)
print(f"stopped after epoch {epoch + 1}, training accuracy {accuracy:.2f}")
xs = np.linspace(-5, 5, 10)
plt.scatter(X[:, 0], X[:, 1], c=y, cmap="coolwarm", s=20)
plt.plot(xs, -(w[0] * xs + b) / w[1], "k-") # the line w·x + b = 0
plt.ylim(-6, 6)
plt.show()stopped after epoch 2, training accuracy 1.00
scikit-learn has a ready-made version, sklearn.linear_model.Perceptron, with the same learning rule.
The XOR problem
Now try XOR: output 1 when exactly one input is 1. Plot the four points and you'll see that no straight line separates the 1s from the 0s:
import numpy as np
from sklearn.linear_model import Perceptron
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y_xor = np.array([0, 1, 1, 0])
p = Perceptron(max_iter=100, tol=None, random_state=0).fit(X, y_xor)
print("perceptron predictions:", p.predict(X), " target:", y_xor)
print("accuracy:", p.score(X, y_xor))perceptron predictions: [0 0 0 0] target: [0 1 1 0]
accuracy: 0.5
A single perceptron can never get all four right. In 1969 Minsky and Papert highlighted exactly this limitation, and interest in neural networks faded for years. The solution — stacking neurons in layers, with smooth activation functions so the whole network can be trained by gradient descent — is the topic of the next lesson.
From step to smooth activations
The step function's "slope" is zero almost everywhere, which gives gradient-based training nothing to work with. Modern networks use smooth or piecewise-linear activations:
import numpy as np
z = np.array([-3.0, -1.0, 0.0, 1.0, 3.0])
step = (z > 0).astype(float)
sigmoid = 1 / (1 + np.exp(-z))
tanh = np.tanh(z)
relu = np.maximum(0, z)
print("z: ", z)
print("step: ", step)
print("sigmoid:", sigmoid.round(3))
print("tanh: ", tanh.round(3))
print("relu: ", relu)z: [-3. -1. 0. 1. 3.]
step: [0. 0. 0. 1. 1.]
sigmoid: [0.047 0.269 0.5 0.731 0.953]
tanh: [-0.995 -0.762 0. 0.762 0.995]
relu: [0. 0. 0. 1. 3.]
ReLU (max(0, z)) is the default in modern deep learning: it's cheap to compute and its slope is 1 for positive inputs, which helps deep networks train.
Test yourself
What does a single perceptron compute before its activation function?
- The product of all inputs
- A weighted sum of the inputs plus a bias
- The maximum input
- The average of the labels
Why can't a single perceptron learn XOR?
- XOR needs more training epochs
- XOR is not linearly separable
- The learning rate is too small
- XOR has too many inputs
In the perceptron rule, what happens to the weights after a correct prediction?
- They are reset to zero
- They are doubled
- They don't change
- They move randomly