Skip to content

MLDay 29 of 50Deep Learning

From Neurons to a Multilayer Perceptron

Logistic regression draws one straight boundary.

7 min read

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 zz from D12. Then it passes zz through an activation, a fixed function that bends it. The two common ones:

  • ReLU (rectified linear unit) keeps a positive zz and turns a negative one into 0.
  • The sigmoid from D12 squashes zz 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 xx feeds two hidden ReLU neurons: h1=ReLU(x)h_1 = \text{ReLU}(x) and h2=ReLU(−x)h_2 = \text{ReLU}(-x). The output adds them: y^=h1+h2\hat{y} = h_1 + h_2.

xx −2 −1 0 1 2
h1=ReLU(x)h_1 = \text{ReLU}(x) 0 0 0 1 2
h2=ReLU(−x)h_2 = \text{ReLU}(-x) 2 1 0 0 0
y^=h1+h2\hat{y} = h_1 + h_2 2 1 0 1 2

The output falls, then rises: a V. No straight line does that. Now delete both ReLUs. Then h1+h2=x+(−x)=0h_1 + h_2 = x + (-x) = 0 for every xx, a flat line. The bend came only from the activation.

The formula

A neuron's output is its activation of the weighted sum:

h=ReLU(z)=max⁡(0, z),z=w⋅x+bh = \text{ReLU}(z) = \max(0,\ z), \qquad z = \mathbf{w}\cdot\mathbf{x} + b
Symbol Meaning
hh the neuron's output, also called its activation
zz the weighted sum: the dot product of weights and inputs, plus the bias (D07)
x\mathbf{x} the neuron's inputs: the features, or the previous layer's outputs
w\mathbf{w}, bb the neuron's own weights and bias, learned in training
max⁡(0, z)\max(0,\ z) the larger of 0 and zz: ReLU passes positives and turns negatives into 0

Worked: w=2w = 2, x=1x = 1 and b=−3b = -3 give z=2×1−3=−1z = 2 \times 1 - 3 = -1, so h=max⁡(0,−1)=0h = \max(0, -1) = 0. The neuron is off. At x=2x = 2, z=1z = 1 and h=1h = 1.

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

Every row
Hours workedz = ŷtarget y
30150
3517.50
40200
4522.55
502510
5527.515

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 w1=0.6w_1 = 0.6, b=−21b = -21), yet it predicts −3 overtime hours for a 30-hour week. Click ReLU and set w1=1w_1 = 1, b=−40b = -40: 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)

A line cuts across the moons; the MLP bends around them

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.

Next · Day 30 · 7 minBackpropagation by Hand← Previous: Day 28 · Project 3: a Credit-Default Model
Not tapped yet