Deep Learning Slides 📂 Introduction · 4 of 18 37 min read

The Multilayer Perceptron (MLP): Neural Networks from the Ground Up

Meet the workhorse of deep learning. This visual, animated guide walks through the MLP layer by layer — input, hidden, and output — plus the forward pass, the Universal Approximation Theorem, vanishing gradients, parameter counting, and working sklearn and PyTorch code you can run today.

The Multilayer Perceptron

Stack simple neurons into layers, wire every one to the next, and something remarkable happens: the network stops needing hand-crafted features and starts learning its own. Meet the workhorse that launched modern deep learning.
Layers & Neurons The Forward Pass Universal Approximation sklearn & PyTorch

Press Next → or use ← → arrow keys

Section 01

What Is an MLP, Really?

Thousands of tiny operators, all connected
Picture a vintage switchboard. A signal enters on one side, and rows of operators pass it along — each one listening to every line before them, deciding how loudly to relay it onward. An MLP is exactly that: neurons arranged in fully-connected layers, where every neuron in one layer feeds every neuron in the next. No neuron sees the whole picture; together they route raw input into a confident answer.
🧠
A "feedforward" network

Information flows in one direction — input → hidden → output — with no loops. That single, tidy assumption is what makes an MLP so easy to train and so widely used as the first neural network anyone learns.

1+Hidden layers stacked between input & output
100%Connections — every neuron links to the next layer
1Direction — signal only flows forward
Section 02

The Three Kinds of Layers

Every MLP is built from three roles. Get these straight and the rest of the network makes sense.

📥
Input Layer
One neuron per feature. It doesn't compute anything — it just holds your data (pixel values, sensor readings, columns of a table) and hands it forward. 3 features → 3 input neurons.
⚙️
Hidden Layer(s)
The engine room. Each neuron takes a weighted sum of the previous layer, adds a bias, and squashes it through a nonlinear activation. Stack more of these to learn richer patterns.
📤
Output Layer
Produces the answer. Softmax for multi-class probabilities, sigmoid for yes/no, or a single linear neuron for regression. Shape it to your task.
💡
The word "perceptron" is a leftover

A single perceptron can only draw a straight line. Stack them with nonlinear activations and you get a multilayer perceptron — able to carve curved, tangled decision boundaries no single line could.

Section 03

The Forward Pass, Step by Step

One neuron does two things: a weighted sum, then a nonlinear squash. Repeat layer by layer and the input becomes a prediction.

z = Wx + b
Weighted sum + bias
a = ReLU(z)
Nonlinear activation
ŷ = softmax(W₃a₂ + b₃)
Final probabilities
StageComputationWhat comes out
Inputx = [x₁, x₂, x₃]Raw feature vector
Hidden 1a₁ = ReLU(W₁·x + b₁)4 activations
Hidden 2a₂ = ReLU(W₂·a₁ + b₂)4 activations
Outputŷ = softmax(W₃·a₂ + b₃)2 class probabilities
🔑
Nonlinearity is the whole trick

Remove the activation function and a hundred stacked layers collapse into a single linear one. ReLU, sigmoid or tanh are what let depth actually buy you expressive power.

Section 04

Anatomy of a 3 → 4 → 4 → 2 Network

Here is a complete MLP: three inputs, two hidden layers of four neurons each, and two outputs — every neuron wired to every neuron in the next layer.

Input · 3 Hidden · 4 Hidden · 4 Output · 2 signal flows left → right (feedforward)
📐
Shorthand you'll see everywhere

People describe an MLP by its layer sizes: [3, 4, 4, 2]. The first number is features in, the last is classes out, and everything between is your design space.

Section 05

Shallow vs Deep: Why Depth Matters

In theory can approximate anything — but may need an impractically wide layer to do it. Fast, simple, great for tabular data and small problems. Struggles to build layered abstractions.
Each layer reuses what the last one learned, composing simple patterns into complex ones. Far more parameter-efficient for images, audio and language — at the cost of trickier training.
🕵️
The detective analogy

A shallow network is one detective trying to crack the whole case alone. A deep network is a relay of detectives — each hands a partial insight to the next, so the final one solves what none could solve solo. Depth is teamwork across layers.

Section 06

What Each Layer Learns

In a deep network, features grow in abstraction layer by layer. For a face-recognition net, the progression is strikingly intuitive:

Edgesbright/dark lines Partseyes · nose · mouth Configurationspart layouts Faceswhole identity

How much depth you need depends on the domain:

DomainTypical depthWhy
Tabular / simple1–3 layersFew interactions to model
ImagesTens of layersDeep visual hierarchy
LanguageDozens+ layersLong-range, abstract structure
Section 07

The Catch: Vanishing Gradients

Depth is powerful, but naive deep networks are hard to train. During backpropagation, the error signal is multiplied layer by layer on its way back — and if those multipliers are small, it shrinks toward zero.

gradient shrinks as it travels back ← Layer 5Layer 4Layer 3Layer 2Layer 1
⚠️
Early layers stop learning

By the time the signal reaches the first layers, it's a whisper — so those layers barely update. The modern fixes: ReLU activations, batch normalization, careful weight initialization, and residual connections.

Section 08

The Universal Approximation Theorem

Give a sculptor enough clay and they can shape any form. The theorem says an MLP with just one hidden layer — given enough neurons — can approximate any continuous function to any accuracy you like. Each neuron adds one more bump or ridge; pile up enough of them and you can mold any surface.
🎯
"Can" is not "will"

The theorem guarantees a network exists — it says nothing about whether gradient descent will find it, how much data you'll need, or how wide the layer must be. In practice, depth reaches the same functions far more efficiently than a single monstrously-wide layer.

1Hidden layer is enough — in theory
Neurons may be needed to hit the guarantee
Depth wins on efficiency in practice
Section 09

Counting the Parameters

Every connection is a weight, and every neuron (except inputs) has a bias. For a layer with n inputs and m neurons: (n × m) weights + m biases.

LayerWeights (n × m)BiasesSubtotal
Input → Hidden 13 × 4 = 12416
Hidden 1 → Hidden 24 × 4 = 16420
Hidden 2 → Output4 × 2 = 8210
Total3→4→4→2 network46

Width is expensive — parameters grow with the product of adjacent layer sizes:

Architecture≈ Parameters
784 → 128 → 10~101,770
784 → 512 → 256 → 10~535,818
784 → 1024 → 1024 → 10~1.87 million
🪤
The width trap

Doubling a layer's width roughly doubles the weights on both sides of it. More parameters means more memory, slower training, and a bigger appetite for data before overfitting sets in.

Section 10

An MLP in scikit-learn

For tabular data and quick baselines, MLPClassifier gives you a working network in a handful of lines — no gradients to hand-code.

from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

# always scale inputs before a neural net
scaler = StandardScaler().fit(X_train)
X_train, X_test = scaler.transform(X_train), scaler.transform(X_test)

clf = MLPClassifier(
    hidden_layer_sizes=(4, 4),   # two hidden layers of 4
    activation="relu",
    solver="adam",
    max_iter=500,
    early_stopping=True,
)
clf.fit(X_train, y_train)
print(clf.score(X_test, y_test))
⚖️
Scale first, always

Neural nets are sensitive to feature magnitude. Standardizing inputs to mean 0 / variance 1 keeps gradients well-behaved and training stable — skip it and the net may never converge.

Section 11

The Same MLP in PyTorch

When you need full control — custom layers, GPUs, your own training loop — define the network as an nn.Module.

import torch.nn as nn

class MLP(nn.Module):
    def __init__(self, in_dim, n_classes):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(in_dim, 64),
            nn.BatchNorm1d(64),
            nn.ReLU(),
            nn.Dropout(0.3),
            nn.Linear(64, 32),
            nn.ReLU(),
            nn.Linear(32, n_classes),
        )

    def forward(self, x):
        return self.net(x)   # logits; softmax lives in the loss

model = MLP(in_dim=20, n_classes=3)
loss_fn = nn.CrossEntropyLoss()
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
🧷
Softmax hides in the loss

The model outputs raw logits; CrossEntropyLoss applies softmax internally for numerical stability. Only add an explicit softmax at inference time when you want probabilities.

Section 12

Three Tools That Make Deep MLPs Work

The difference between an MLP that trains and one that stalls or overfits usually comes down to these three:

📊
Batch Normalization
Re-centers and re-scales each layer's inputs on the fly. Tames vanishing gradients, lets you use higher learning rates, and speeds up convergence dramatically.
🎲
Dropout
Randomly switches off a fraction of neurons each step, forcing the network to build redundant representations. A cheap, powerful guard against overfitting.
ReLU & friends
ReLU keeps gradients alive for positive inputs. Variants like LeakyReLU and GELU fix its one weakness — "dead" neurons stuck at zero.
🔧
Order matters

A common, reliable block is Linear → BatchNorm → ReLU → Dropout. Normalize before the nonlinearity, drop out after it.

Section 13

7 Golden Rules for Building MLPs

  Field-tested defaults
1Scale your inputs. Standardize to mean 0, variance 1 before the first layer — non-negotiable.
2Start small, then grow. Begin with 1–2 hidden layers; add depth/width only when the data demands it.
3Default to ReLU in hidden layers. Match the output activation to the task — softmax, sigmoid, or linear.
4Regularize early. Dropout and weight decay cost little and prevent a lot of overfitting.
5Use BatchNorm for deeper nets — it stabilizes training and unlocks higher learning rates.
6Watch parameters vs data. Aim for enough samples per weight; more parameters need more data.
7Know when to switch. For images reach for CNNs, for sequences RNNs/Transformers — MLPs shine on tabular data.
🚀
You now know the workhorse of deep learning

The MLP is the foundation every fancier architecture builds on. Master its layers, forward pass, and training tricks, and CNNs, RNNs and Transformers become variations on a theme you already understand.