MLDay 29 of 50Deep Learning
From Neurons to a Multilayer Perceptron
Logistic regression draws one straight boundary.
Logistic regression draws one straight boundary. Real classes often curve: picture two half-moons of points hooked into each other. No straight cut separates them, but a stack of simple units can bend around them.
The idea
A neuron does two things. First it takes a weighted sum of its inputs plus a bias, the score from D12. Then it passes through an activation, a fixed function that bends it. The two common ones:
- ReLU (rectified linear unit) keeps a positive and turns a negative one into 0.
- The sigmoid from D12 squashes into a number between 0 and 1.
A layer is a row of neurons that all read the same inputs. A multilayer perceptron (MLP) chains layers: each layer's outputs are the next layer's inputs. The layers between the input and the output are hidden layers.
The activation is what makes stacking worth it. Without it, every layer is a weighted sum, and a weighted sum of weighted sums is just one more weighted sum. Ten such layers still draw one straight boundary. With ReLU, each neuron adds a kink, and the next layer adds the kinked pieces up into a bent boundary. Training picks all the weights to lower the loss (log loss for a classifier), by gradient descent (D09).
A tiny example
One input feeds two hidden ReLU neurons: and . The output adds them: .
| −2 | −1 | 0 | 1 | 2 | |
|---|---|---|---|---|---|
| 0 | 0 | 0 | 1 | 2 | |
| 2 | 1 | 0 | 0 | 0 | |
| 2 | 1 | 0 | 1 | 2 |
The output falls, then rises: a V. No straight line does that. Now delete both ReLUs. Then for every , a flat line. The bend came only from the activation.
The formula
A neuron's output is its activation of the weighted sum:
| Symbol | Meaning |
|---|---|
| the neuron's output, also called its activation | |
| the weighted sum: the dot product of weights and inputs, plus the bias (D07) | |
| the neuron's inputs: the features, or the previous layer's outputs | |
| , | the neuron's own weights and bias, learned in training |
| the larger of 0 and : ReLU passes positives and turns negatives into 0 |
Worked: , and give , so . The neuron is off. At , and .
Try it
Can one neuron learn overtime?
Each weight says how much its feature counts; the bias b is the starting point. Move the sliders to bring the predictions close to the targets.
z = 0.5·Hours worked + 0
| Hours worked | z = ŷ | target y |
|---|---|---|
| 30 | 15 | 0 |
| 35 | 17.5 | 0 |
| 40 | 20 | 0 |
| 45 | 22.5 | 5 |
| 50 | 25 | 10 |
| 55 | 27.5 | 15 |
row 1: z = 15RMSE 16.425
The target is overtime: the hours past 40 in a week. With no activation the neuron is a straight line, and its RMSE (the typical miss, from D05) starts at about 16.4. The best line gets to about 2.2 (near , ), yet it predicts −3 overtime hours for a 30-hour week. Click ReLU and set , : the RMSE drops to 0, because the kink sits at 40 hours.
In code
scikit-learn's MLPClassifier is an MLP for classes. (16, 16) is its hidden_layer_sizes: two hidden
layers of 16 neurons each, and activation="identity" removes the activation. The data is 500 points in two noisy half-moons,
scored on a held-out quarter
(D06).
# script_id: day_029_neurons_to_mlp/moons
from sklearn.datasets import make_moons
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
X, y = make_moons(n_samples=500, noise=0.2, random_state=42) # two interleaved half-moons
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
models = {
"logistic regression": LogisticRegression(),
"MLP, no activation": MLPClassifier((16, 16), activation="identity", max_iter=2000, random_state=42),
"MLP, ReLU": MLPClassifier((16, 16), activation="relu", max_iter=2000, random_state=42),
}
for name, model in models.items():
model.fit(X_train, y_train)
print(f"{name:20s} test accuracy {model.score(X_test, y_test):.3f}")
mlp = models["MLP, ReLU"]
print("weight matrices:", [w.shape for w in mlp.coefs_])
print("weights and biases:", sum(w.size for w in mlp.coefs_) + sum(b.size for b in mlp.intercepts_))
print("training passes:", mlp.n_iter_, "| output activation:", mlp.out_activation_)
logistic regression test accuracy 0.856
MLP, no activation test accuracy 0.856
MLP, ReLU test accuracy 0.984
weight matrices: [(2, 16), (16, 16), (16, 1)]
weights and biases: 337
training passes: 597 | output activation: logistic
Without an activation, 337 weights and biases score exactly what logistic regression does. ReLU lifts the
accuracy from 0.856 to 0.984, after 597 passes over the training data. The output neuron is a sigmoid (logistic), so the last layer is logistic
regression, run on 16 features that the hidden layers learned. The chart shows both boundaries:
# script_id: day_029_neurons_to_mlp/moons
import os
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
FIG_DIR = Path(os.environ.get("ML_FIG_DIR", "figures"))
FIG_DIR.mkdir(exist_ok=True)
g1, g2 = np.meshgrid(np.linspace(-1.6, 2.6, 300), np.linspace(-1.1, 1.6, 300))
grid = np.c_[g1.ravel(), g2.ravel()] # every point of the plot, to colour by class
fig, axes = plt.subplots(1, 2, figsize=(6, 4), sharey=True)
for ax, name in zip(axes, ["logistic regression", "MLP, ReLU"]):
p = models[name].predict_proba(grid)[:, 1].reshape(g1.shape)
ax.contourf(g1, g2, p, levels=[0, 0.5, 1], colors=["#cfe0f3", "#f6d5c4"])
ax.contour(g1, g2, p, levels=[0.5], colors="black", linewidths=1) # the boundary, p = 0.5
ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap="coolwarm", s=10, edgecolors="none")
ax.set(title=f"{name}: {models[name].score(X_test, y_test):.3f}", xlabel="x1")
axes[0].set_ylabel("x2")
fig.suptitle("A line cuts across the moons; the MLP bends around them")
fig.tight_layout()
fig.savefig(FIG_DIR / "moons_boundaries.png", dpi=120)
plt.close(fig)

The MLP's boundary is a chain of straight pieces joined at kinks, which is what adding up ReLUs gives.
Quick check
Quick check
1. A ReLU neuron has w = (1, −1), b = 0.5 and gets x = (2, 3). What does it output?
2. An MLP has three hidden layers but no activation. What boundary can it draw?
3. What does MLPClassifier((16, 16)) build?
Next
D30: Backpropagation by Hand opens up training: how each of those 337 weights and biases learns which way to move.