LeNet-5 is a convolutional neural network (CNN) for handwritten character recognition that alternates convolutional and subsampling layers and ends with fully connected layers. It was presented in 1998 by LeCun et al. at AT&T Labs in a long paper on document recognition. The "5" in the name is not the number of layers but the number in a series of models that went LeNet-1, LeNet-4, and so on.
Until then, character recognition mainly relied on extracting hand-designed features and feeding them to a classifier. LeNet-5 takes raw pixel values as input and trains both the feature extraction and the classification parts together with backpropagation. The paper achieved this with practical accuracy by combining three mechanisms suited to images.
Local receptive fields: Each unit looks only at a small region of the input (such as 5×5).
Weight sharing: All units within the same feature map use the same weights (this is convolution).
Subsampling: The height and width of feature maps are halved, making the network robust to shifts in position.
The main results of the paper are as follows.
On MNIST (handwritten digits, 60,000 training and 10,000 test images), created alongside the paper, it achieved a test error rate of 0.95%. Augmenting the training data with distortions brought it to 0.8%.
With about 60,000 trainable parameters, it matched or exceeded the accuracy of fully connected multilayer perceptrons (2.45–4.7% error) and computationally expensive SVMs, using little computation and memory.
LeNet-5's form, "extract features with convolution and pooling, then classify with fully connected layers", was carried over directly into later models such as AlexNet and VGG.
Architecture
LeNet-5 consists of 7 layers, not counting the input, and every layer has trainable parameters. The left side of the figure at the top of the article shows the overall flow; the right side shows the connections of layer C3. The paper denotes convolutional layers by C, subsampling layers by S, and fully connected layers by F, followed by the layer index.
An image flows through the following steps.
Input: A 32×32 image. It is larger than the MNIST characters (at most 20×20) so that stroke end points and corners can appear at the center of the receptive fields of the highest-level feature detectors.
C1: A 5×5 convolution produces 6 feature maps of 28×28.
S2: 2×2 subsampling yields 6 feature maps of 14×14.
C3: A 5×5 convolution produces 16 feature maps of 10×10. Each takes as input only a fixed subset of the 6 maps in S2 (explained below).
S4: 2×2 subsampling yields 16 feature maps of 5×5.
C5: A 5×5 convolution produces 120 feature maps of 1×1. It connects to all feature maps of S4.
F6: A fully connected layer of 84 units.
Output: An RBF unit for each of the 10 classes outputs its distance from the F6 output. The class with the smallest value is the answer.
The size of each layer is as follows (Section II.B of the paper).
Layer
Operation
Output shape
Parameters
Connections
C1
5×5 convolution
6@28×28
156
122,304
S2
2×2 subsampling
6@14×14
12
5,880
C3
5×5 convolution (partially connected)
16@10×10
1,516
151,600
S4
2×2 subsampling
16@5×5
32
2,000
C5
5×5 convolution
120@1×1
48,120
48,120
F6
Fully connected
84
10,164
10,164
Output
RBF (distance)
10
Fixed
—
"6@28×28" means six 28×28 feature maps. The whole network has 340,908 connections, but thanks to weight sharing the trainable parameters stay at about 60,000. Because C5's input is exactly 5×5, it computes the same thing as a fully connected layer, but it is treated as a convolutional layer because a larger input image would make its output larger than 1×1.
Subsampling layers (S2, S4)
Each unit looks at a 2×2 region (non-overlapping) of the corresponding feature map in the previous layer and computes the following.
Sum the four inputs.
Multiply by a trainable coefficient and add a trainable bias (one coefficient and one bias per feature map).
Pass the result through the activation function.
This is what is now called average pooling, with a trainable coefficient and bias added. The paper explains that with a small coefficient the layer merely blurs the input, while with a large one it acts like a "noisy OR" or a "noisy AND".
Connections of C3
The 16 feature maps of C3 do not take all 6 maps of S2 as input, only fixed combinations of them (Table I of the paper).
Maps 0–5: 3 adjacent maps each
Maps 6–11: 4 adjacent maps each
Maps 12–14: 4 non-adjacent maps each
Map 15: all 6 maps
The paper gives two reasons. One is to keep the number of connections down; the other is to break symmetry by giving each feature map different inputs, so that each learns different (complementary) features.
Activation function
Each unit up to F6 passes ai, the dot product of its inputs and weights plus a bias, through a scaled tanh.
xi=f(ai),f(a)=Atanh(Sa)
The paper uses A=1.7159 and S=2/3. Then f(1)=1 and f(−1)=−1, so input and output magnitudes roughly match over the normal operating range. The paper calls this function a "sigmoid squashing function"; it is not the sigmoid function itself.
Output layer (RBF units)
The 10 output units are radial basis function (RBF) units that compute Euclidean distances. With F6 outputs xj and parameters wij of the unit for class i, the output is given by the following equation.
yi=j∑(xj−wij)2
yi measures how far the F6 output is from the "prototype vector" of class i; the smaller it is, the more likely the class. The prototype vectors are not learned but fixed to hand-chosen values of −1 or +1. They are drawings of each character as 7×12 black-and-white bitmaps, which is why F6 has 84 units. The aim is to give similar characters (such as capital O and the digit 0) similar prototypes, so that a downstream linguistic post-processor can more easily correct confusions.
Training
LeNet-5 is trained by computing the gradient of the loss function with backpropagation and updating the weights little by little. For connections that share weights, the gradient is computed for each connection and then summed to give the gradient of the single shared parameter.
Loss function
The simplest loss makes the output of the RBF unit for the correct class (its distance from the prototype) small. For P training examples with correct classes Dp, it is given by the following equation, which corresponds to mean squared error.
E(W)=P1p=1∑PyDp(Zp,W)
This equation only pulls the correct class closer and does not push the other classes away. Moreover, if the RBF parameters are also trained, it collapses to a solution in which all prototypes and the F6 output are equal, ignoring the input and driving the loss to 0. The paper therefore presents the following loss (the MAP criterion), which adds a term that pushes up the distances of the other classes.
j is a positive constant that plays the role of a "none of the classes" answer. The second term has the same form as the softmax denominator in what is now called cross-entropy.
Preparing inputs and weights
Input normalization: The background (white) is set to −0.1 and the foreground (black) to 1.175. This makes the input mean roughly 0 and variance roughly 1, which speeds up training.
Initial weights: With Fi the number of inputs to a unit (fan-in), weights are drawn from a uniform distribution between −2.4/Fi and 2.4/Fi. This keeps the spread of the weighted sums within the range where the activation function works well for every unit (the same idea as LeCun initialization).
Optimization
The paper used stochastic gradient descent with a method that adjusts the learning rate of each parameter using an approximation of the second derivative (the diagonal of the Hessian), called the stochastic diagonal Levenberg-Marquardt method. The MNIST training settings are as follows.
Item
Value
Training data
60,000 MNIST images (28×28 images padded to 32×32)
Number of passes
20 passes over the whole training set
Global learning rate
0.0005 for the first 2 passes, 0.0002 for the next 3, 0.0001 for the next 3, 0.00005 for the next 4, then 0.00001
Second-derivative approximation
Recomputed on 500 images before each pass and fixed during that pass
Training time
2–3 days on a single 200 MHz CPU
Why High Accuracy with Few Parameters
LeNet-5 achieved high accuracy with few parameters because it built constraints matched to the nature of images into the network architecture. The paper explains this as follows.
Local receptive fields: In images, nearby pixels are strongly correlated, and local features such as edges, corners, and line end points are the cues. Having each unit look only at a small region makes such features easier to extract.
Weight sharing: A feature detector useful in one place is also useful elsewhere in the image. Using the same weights across the whole image means that when the input shifts, the feature map simply shifts with it. A fully connected network needs large amounts of data to learn shifted characters, but convolution has this property built in.
Subsampling: Once a feature is detected, its rough position relative to other features matters more than its exact location. Deliberately coarsening the positional information by halving height and width makes the network robust to variations and shifts in handwriting. As layers progress, the spatial size shrinks while the number of feature maps grows, preserving the amount of information.
As an everyday analogy, to recognize the digit "7" it is enough to know that "there is the end of a horizontal stroke at the top left", "there is a corner at the top right", and "there is the end of a vertical stroke at the bottom"; the exact pixel positions are not needed. LeNet-5 expresses this idea in how it stacks its layers.
Weight sharing also reduces the number of free parameters. The paper explains that this lowers the model's "capacity" and reduces the gap between training and test error. Indeed, against 340,908 connections, there are only about 60,000 trainable parameters.
The paper reports that overfitting, where test error starts rising as training continues, was not observed when training LeNet-5 on MNIST. As a possible reason it suggests that, with a relatively large learning rate, the weights keep oscillating rather than settling into one valley, which favors solutions in wide valleys (an effect similar to regularization).
Experimental Results
Error rates on MNIST (10,000 test images, %; Section III and Figure 9 of the paper)
LeNet-5 gave the best result as a single model. The test error settled at 0.95% after about 10 passes over the training set, and the training error dropped to 0.35% by the 19th pass.
Effect of more training data
Varying the training set size among 15,000, 30,000, and 60,000 showed that more data gave lower test error. The paper therefore trained on the original 60,000 images plus 540,000 images distorted by random combinations of translation, scaling, squeezing, and horizontal shearing. With the same number of passes (20 passes of 60,000 images each), the test error dropped from 0.95% to 0.8%. This is the effect of what is now called data augmentation.
Computation and memory
The paper compares not only accuracy but also the computation needed to recognize one character and the memory required.
K-nearest neighbors must keep all 60,000 training images (about 24 MB) at hand.
An SVM needs about 14 million multiply-adds per character. Even a reduced SVM (RS-SVM) needs 650,000, about 1.6 times LeNet-5.
Fully connected networks, meanwhile, only got down to 2.95% error even when going from 1 to 2 hidden layers.
Neural networks run with far less computation and memory than memory-based methods, and among them LeNet-5, with its convolutional structure, gave the best accuracy.
Once MNIST error rates fall below 1%, the differences become very small. The paper itself notes that the uncertainty of the error rates in Figure 9 is about 0.1%. Keep this margin in mind when comparing differences such as 0.95% versus 0.8%.
Practical Considerations
Keep the following points in mind when using or reproducing LeNet-5.
The commonly seen "LeNet-5" may differ from the paper: Implementations in textbooks and tutorials often replace subsampling with max pooling, the activation function with ReLU, C3 with full connections, and the RBF output with a fully connected layer and a softmax function. Such variants still learn MNIST well, but when comparing with the paper's numbers, check what differs.
Use 32×32 inputs: MNIST images are 28×28, so add 2 pixels of padding on each side to make them 32×32. If fed at 28×28, the output of C5 will not be 1×1.
The paper's optimizer is uncommon today: The stochastic diagonal Levenberg-Marquardt method is not built into today's deep learning libraries. Training with SGD or Adam changes settings such as the learning rate from those in the paper.
Too small for large images: LeNet-5 is a model of about 60,000 parameters designed for 32×32 black-and-white characters. For color natural images or large images, use deeper models from AlexNet onward.
If the RBF prototype vectors of the output are also trained, using the paper's first loss (which only shrinks the distance to the correct class) makes all prototypes identical and collapses to a solution that ignores the input. Either keep the prototypes fixed or use a loss with a term that pushes up distances to the other classes (the MAP criterion).
Comparison with Other Models
Comparing LeNet-5 with later image classification CNNs from the same viewpoint gives the following (parameter counts and inputs are the values from each paper).
All three share the same skeleton: extract features with convolutions, increase the number of feature maps while shrinking the spatial size, and classify with fully connected layers at the end. AlexNet can be seen as scaling this skeleton up for large data (ImageNet) and GPUs, with ReLU and dropout making training faster and more stable.
The differences from methods without convolution are as follows.
Method
Use of image structure
MNIST error rate
Weakness
Fully connected network
None (unchanged if pixel order is permuted)
2.45–4.7%
Needs large amounts of data to learn shifts and distortions
SVM
None
1.4%
Large computation and memory
LeNet-5
Local receptive fields, weight sharing, subsampling
0.95%
Architecture must be designed by hand
Rough guidelines for choosing are as follows.
Learning or experimenting with CNN basics: LeNet-5 is small and trains quickly even on a CPU, making it well suited to seeing how convolution, pooling, and fully connected layers work.
Classifying small black-and-white images: For tasks like MNIST, LeNet-5 (or a variant with ReLU and max pooling) gives sufficient accuracy.
Classifying natural images: Choose deeper models such as ResNet.
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
"""
Example of training LeNet-5, built as described in Section II.B of the paper (LeCun et al. 1998), on MNIST
- Activation function is 1.7159 × tanh(2/3 × a)
- S2 and S4 apply "2×2 sum × trainable coefficient + bias" followed by the activation function
- C3 uses the connections of Table I (only some feature maps of S2)
- Output is RBF (squared distance between the F6 output and fixed prototype vectors). Loss is the MAP criterion of Eq. (9)
PyTorch has no built-in LeNet-5
"""
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
# Input: pad 28×28 to 32×32; background -0.1, foreground 1.175 (ToTensor gives background 0, foreground 1)
transform = transforms.Compose([
transforms.Pad(2),
transforms.ToTensor(),
transforms.Lambda(lambda x: x * 1.275 - 0.1),
])
train_loader = DataLoader(datasets.MNIST('./data', train=True, download=True, transform=transform), batch_size=32, shuffle=True)
test_loader = DataLoader(datasets.MNIST('./data', train=False, download=True, transform=transform), batch_size=1000)
def scaled_tanh(a):
return 1.7159 * torch.tanh(2.0 / 3.0 * a) # Eq. (6). f(1)=1, f(-1)=-1
class Subsampling(nn.Module):
"""Sum the 4 inputs of a 2×2 region, multiply by a per-map coefficient and add a bias (2 × maps parameters)"""
def __init__(self, channels):
super().__init__()
self.coef = nn.Parameter(torch.ones(1, channels, 1, 1))
self.bias = nn.Parameter(torch.zeros(1, channels, 1, 1))
def forward(self, x):
s = F.avg_pool2d(x, 2) * 4 # 2×2 sum (non-overlapping)
return scaled_tanh(s * self.coef + self.bias)
# Table I: S2 feature maps used by each C3 feature map (column)
C3_TABLE = [
[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 0], [5, 0, 1],
[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 0], [4, 5, 0, 1], [5, 0, 1, 2],
[0, 1, 3, 4], [1, 2, 4, 5], [0, 2, 3, 5],
[0, 1, 2, 3, 4, 5],
]
class C3(nn.Module):
"""5×5 convolution with weights of unconnected inputs fixed to 0 (1,516 parameters)"""
def __init__(self):
super().__init__()
self.conv = nn.Conv2d(6, 16, 5)
mask = torch.zeros(16, 6, 1, 1)
for out_ch, ins in enumerate(C3_TABLE):
mask[out_ch, ins] = 1
self.register_buffer('mask', mask)
def forward(self, x):
return F.conv2d(x, self.conv.weight * self.mask, self.conv.bias)
class LeNet5(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.c1 = nn.Conv2d(1, 6, 5) # 32×32 → 6@28×28
self.s2 = Subsampling(6) # → 6@14×14
self.c3 = C3() # → 16@10×10
self.s4 = Subsampling(16) # → 16@5×5
self.c5 = nn.Conv2d(16, 120, 5) # → 120@1×1
self.f6 = nn.Linear(120, 84)
# RBF prototypes (not trained). The paper uses 7×12 character bitmaps (±1); here ±1 is chosen at random
self.register_buffer('prototypes', torch.randint(0, 2, (num_classes, 84)).float() * 2 - 1)
for m in self.modules(): # Appendix A: uniform distribution of ±2.4 / fan-in
if isinstance(m, (nn.Conv2d, nn.Linear)):
fan_in = m.weight[0].numel()
nn.init.uniform_(m.weight, -2.4 / fan_in, 2.4 / fan_in)
nn.init.zeros_(m.bias)
def forward(self, x):
x = scaled_tanh(self.c1(x))
x = self.s2(x)
x = scaled_tanh(self.c3(x))
x = self.s4(x)
x = scaled_tanh(self.c5(x)).flatten(1)
x = scaled_tanh(self.f6(x)) # [N, 84]
return torch.cdist(x, self.prototypes) ** 2 # Eq. (7): squared distance to each class prototype [N, 10]
def map_loss(y, target, j=1.0):
"""Eq. (9): correct-class distance + log(e^{-j} + Σ e^{-y_i}). j is a positive constant (set to 1 here)"""
y_correct = y.gather(1, target[:, None]).squeeze(1)
others = torch.cat([y.new_full((y.size(0), 1), j), y], dim=1)
return (y_correct + torch.logsumexp(-others, dim=1)).mean()
model = LeNet5().to(device)
# The paper uses stochastic diagonal Levenberg-Marquardt; SGD is used instead here (learning rate does not match the paper's values)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
for epoch in range(20): # The paper uses 20 passes over the training set
model.train() # This form has no dropout or BN, so train/eval behave the same
for images, labels in train_loader:
images, labels = images.to(device), labels.to(device)
loss = map_loss(model(images), labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
model.eval()
correct = 0
with torch.no_grad():
for images, labels in test_loader:
images, labels = images.to(device), labels.to(device)
pred = model(images).argmin(1) # The class with the smallest distance is the answer
correct += (pred == labels).sum().item()
print(f"Test error: {100 * (1 - correct / len(test_loader.dataset)):.2f}%")
FAQ
Q. Is the "5" in LeNet-5 the number of layers?
A.
No. It is the number in a series of models developed by LeCun et al. (LeNet-1, LeNet-4, LeNet-5, and so on). LeNet-5 has 7 layers not counting the input (C1, S2, C3, S4, C5, F6, and the output). The paper explains that the models grew from LeNet-1 (about 2,600 parameters), designed for the computers of around 1989, to LeNet-4 and LeNet-5 as data and hardware advanced.
Q. If building LeNet-5 today, is it fine to use ReLU and max pooling?
A.
Yes. For tasks like MNIST, a combination of ReLU, max pooling, fully connected layers, and cross-entropy also trains well. However, that is a different form from the LeNet-5 in the paper, so when comparing with the paper's error rate (0.95%) or claiming to have "reproduced LeNet-5", state clearly what was changed.
Q. Why are MNIST's 28×28 images padded to 32×32?
A.
So that features at the edges of the image can also be captured at the center of the receptive fields of the feature detectors in the top convolutional layer. According to the paper, with a 32×32 input the centers of C3's receptive fields fall within the central 20×20 region of the input, which exactly holds an MNIST character (at most 20×20). It is also the size at which stacking 5×5 convolutions and subsampling makes the output of C5 exactly 1×1.