AI Logic

Architectures

Multilayer Perceptron (MLP)

Updated:

MLP architecture. Left: the overall flow from input to prediction. Right: an illustration of full connectivity and the computation of one hidden layer

Background and overview

The MLP (Multi-Layer Perceptron) is the most basic neural network, built by alternating fully connected layers and activation functions.

It grew out of the perceptron proposed by Rosenblatt in 1958. A perceptron has only one layer, so it can solve only problems that can be separated by a straight line (plane). For example, XOR, which returns 1 when exactly one of two inputs is 1, cannot be separated by a single line and so cannot be solved.

The MLP solves this by stacking layers. In 1986, Rumelhart et al. showed that networks with stacked layers can be trained with backpropagation, and MLPs came into wide use.

Even with a single hidden layer, an MLP can approximate any continuous function to any desired accuracy if it has enough nodes (the universal approximation theorem, proved in 1989 by Cybenko and by Hornik et al.). However, the theorem only states that weights achieving the approximation exist; it guarantees neither that training will find them nor how many nodes are needed.

MLPs are still used as components of many models. The "feed-forward layer" in each layer of the Transformer is a two-layer MLP, and MLP-Mixer, along with TSMixer and TTM built on it, constructs the entire model from MLPs alone.

Theory

An MLP consists of an input layer, hidden layers, and an output layer. Every node in one layer is connected to every node in the next, so each layer is called a fully connected layer.

Information flows as follows.

  1. The input is turned into a vector x\boldsymbol{x} of length dd.
    • For an image, the pixels are flattened into a single row (length 784 for a 28×28 image).
  2. A hidden layer multiplies by weights and sums (Wx+b\boldsymbol{W}\boldsymbol{x} + \boldsymbol{b}), then applies an activation function φ\varphi.
  3. Step 2 is repeated once per hidden layer (LL times).
  4. The last fully connected layer (the output layer) maps to the number of outputs kk.
    • For classification, the outputs are turned into probabilities with the softmax function, and the model is trained with cross-entropy.

An MLP with one hidden layer can be written as follows.

h=φ(W1x+b1),y=W2h+b2\boldsymbol{h} = \varphi(\boldsymbol{W}_1 \boldsymbol{x} + \boldsymbol{b}_1), \qquad \boldsymbol{y} = \boldsymbol{W}_2 \boldsymbol{h} + \boldsymbol{b}_2

Here, h\boldsymbol{h} is the hidden layer output (a vector of length hh), W1\boldsymbol{W}_1 is an h×dh \times d weight matrix, W2\boldsymbol{W}_2 is a k×hk \times h weight matrix, and b1,b2\boldsymbol{b}_1, \boldsymbol{b}_2 are biases. The weights and biases are updated with an optimizer such as Adam, using gradients computed by backpropagation.

Without activation functions, any number of stacked fully connected layers is equivalent to a single fully connected layer, because the matrices can be combined, as in W2(W1x)=(W2W1)x\boldsymbol{W}_2(\boldsymbol{W}_1\boldsymbol{x}) = (\boldsymbol{W}_2\boldsymbol{W}_1)\boldsymbol{x}. Stacking layers is meaningful only because the activation functions in between allow curved decision boundaries.

MLPs also have the following weaknesses.

  • Because the input is flattened into a single row, structure such as the spatial arrangement of image pixels or the order of a time series cannot be exploited. Models that exploit the data's structure are commonly used instead, such as a CNN for images and a Transformer for sequences.
  • Because every node is connected, large inputs mean many parameters. Connecting 784 inputs to 256 nodes alone requires about 200,000 weights.
  • Deeper networks become harder to train because of vanishing gradients and more prone to overfitting. ReLU and dropout are used to mitigate these problems.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from tqdm import tqdm

'''
Image classification task on MNIST data
'''

# Hyperparameters
batch_size = 64       # batch size
epochs = 5            # number of epochs
learning_rate = 1e-3  # learning rate
hidden_dim = 256      # number of nodes in each hidden layer

# 'cuda' if CUDA is available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'

# Datasets and loaders
transform = transforms.Compose([
  transforms.ToTensor(),
  transforms.Normalize((0.1307,), (0.3081,))
])

train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size)


# MLP model (fully connected layer -> ReLU twice -> output layer)
class MLP(nn.Module):
  def __init__(self, in_dim=28 * 28, hidden_dim=256, num_classes=10):
    super().__init__()
    self.layers = nn.Sequential(
      nn.Flatten(),                       # [B, 1, 28, 28] -> [B, 784]
      nn.Linear(in_dim, hidden_dim),
      nn.ReLU(),
      nn.Linear(hidden_dim, hidden_dim),
      nn.ReLU(),
      nn.Linear(hidden_dim, num_classes)  # softmax is computed inside the loss function
    )

  def forward(self, x):
    return self.layers(x)


# Training and evaluation
model = MLP(hidden_dim=hidden_dim).to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

# Training loop
for epoch in tqdm(range(epochs)):
  model.train()
  for images, labels in train_loader:
    images, labels = images.to(device), labels.to(device)
    optimizer.zero_grad()
    outputs = model(images)
    loss = criterion(outputs, labels)
    loss.backward()
    optimizer.step()

# Evaluation
model.eval()
correct = 0
total = 0
with torch.no_grad():
  for images, labels in test_loader:
    images, labels = images.to(device), labels.to(device)
    outputs = model(images)
    _, predicted = torch.max(outputs, 1)
    total += labels.size(0)
    correct += (predicted == labels).sum().item()

accuracy = 100 * correct / total
print(f"Test Accuracy: {accuracy:.2f}%")

FAQ

Q. What is the difference between an MLP and a perceptron?
A.

A perceptron has a single layer and outputs either 0 or 1. An MLP stacks layers with smooth activation functions in between, which makes it trainable with backpropagation. As a result, it can also solve problems that cannot be separated by a straight line, such as XOR.

Q. How should the number of hidden layers and nodes be chosen?
A.

There is no fixed answer. A common approach is to start with 1–2 hidden layers and a few hundred nodes, then adjust while watching accuracy on validation data. Making the network too large invites overfitting, so combine it with techniques such as dropout.

Q. Can an MLP be used for images or time series?
A.

It can, but because the input is flattened into a single row, it cannot exploit the arrangement of pixels or the order in time. It classifies small images such as MNIST well enough, but for large images or long sequences, CNNs, Transformers, or MLPs with a structured design such as MLP-Mixer are better suited.

References

  1. Rosenblatt, F. (1958). The perceptron: A probabilistic model for information storage and organization in the brain. Psychological Review, 65(6), 386–408.
  2. Rumelhart, D. E., Hinton, G. E., & Williams, R. J. (1986). Learning representations by back-propagating errors. Nature, 323, 533–536.
  3. Cybenko, G. (1989). Approximation by superpositions of a sigmoidal function. Mathematics of Control, Signals, and Systems, 2, 303–314.
  4. Hornik, K., Stinchcombe, M., & White, H. (1989). Multilayer feedforward networks are universal approximators. Neural Networks, 2(5), 359–366.
  5. I. Goodfellow, Y. Bengio, and A. Courville, "Deep Learning," MIT Press, 2016, Chapter 6: Deep Feedforward Networks (6.1 XOR, 6.4.1 Universal Approximation Theorem).
  6. A. Zhang, Z. C. Lipton, M. Li, and A. J. Smola, "Dive into Deep Learning," Section 5.1 Multilayer Perceptrons.
  7. Vaswani, A., et al. (2017). Attention Is All You Need. NeurIPS 2017 (Section 3.3 Position-wise Feed-Forward Networks).
  8. Tolstikhin, I., et al. (2021). MLP-Mixer: An all-MLP Architecture for Vision. NeurIPS 2021.