AI Wiki中文/EN

LeNet: the original architecture and its variants

LeNet

Trace all stages of LeNet-5, reconstruct 60000 trainable parameters, and distinguish distance outputs from probabilities.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with an experiment

Two programs are both called LeNet-5. One uses trainable subsampling and partly connected feature maps; the other uses fixed pooling and connects every input map to every output map. They need not have the same parameter count or output meaning.

LeNet is a family of convolutional networks associated with document recognition. This chapter follows the LeNet-5 architecture described in the 1998 paper closely enough to expose its distinctive decisions: shared spatial kernels, trainable subsampling, a sparse C 3 connection pattern, an 84-dimensional representation and distance-based output units. The complete forward program uses newly sampled weights and a synthetic codebook. It is not a trained digit recognizer.

Start by predicting the result for a completely zero input with zero biases. Every hidden activation will be zero. Each fixed 84-entry prototype contains only minus one and plus one, so every squared distance will be 84. Equal scores reveal a tie, not confident recognition.

The model and its assumptions

A convolutional feature map uses one kernel repeatedly across spatial positions. If output map o receives input maps in SoS_o, a valid five-by-five cross-correlation is:

ao(y,x)=bo+∑c∈So∑i=04∑j=04wocijhc(y+i,x+j).a_o(y,x)=b_o+\sum_{c\in S_o}\sum_{i=0}^{4}\sum_{j=0}^{4}w_{ocij}h_c(y+i,x+j).

Deep-learning implementations commonly call this convolution; the kernel-orientation convention is explicit here. The paper uses a scaled hyperbolic tangent, with the inspected appendix giving:

f(a)=1.7159tanh⁡(23a).f(a)=1.7159\tanh\left(\frac23a\right).

A subsampling unit sums a nonoverlapping two-by-two region, multiplies by a learned per-map coefficient and adds a learned bias before applying f:

sc(y,x)=f(αc∑i=01∑j=01hc(2y+i,2x+j)+βc).s_c(y,x)=f\left(\alpha_c\sum_{i=0}^{1}\sum_{j=0}^{1}h_c(2y+i,2x+j)+\beta_c\right).

This is not fixed average pooling. Our initial αc=1/4\alpha_c=1/4 averages before the nonlinearity, but learning can change that coefficient and the bias. The paper’s architecture and connection table establish the following shapes and free-parameter counts when the output codebook is held fixed. LeCun et al., 1998

StageOutputTrainable parameters
C 128×28×6156
S 214×14×612
C 310×10×161516
S 45×5×1632
C 51×1×12048120
F 68410164
RBF codebook10 distances0 in this fixed-codebook example

C 3 has 60 input-map/output-map connections. Each has 25 kernel weights, and each of 16 outputs has a bias: 60×25+16=151660\times25+16=1516. The subsets overlap, so they are not simply the disjoint groups of a modern grouped convolution. C 5 is spatially one-by-one for this input size; its five-by-five kernels still encode a convolutional construction.

For an F 6 vector h and class prototype tkt_k, the output energy is a squared distance:

dk=∑j=184(hj−tkj)2.d_k=\sum_{j=1}^{84}(h_j-t_{kj})^2.

Smaller energy means a closer prototype. It is not a probability. The paper also describes a competitive loss with a positive constant rejection energy J. For one labeled example y, written in our notation:

ℓ=dy+log⁡(e−J+∑ke−dk),pk=e−dke−J+∑re−dr.\ell=d_y+\log\left(e^{-J}+\sum_k e^{-d_k}\right),\qquad p_k=\frac{e^{-d_k}}{e^{-J}+\sum_r e^{-d_r}}.

Differentiation gives ∂ℓ/∂dk=1[k=y]−pk\partial\ell/\partial d_k=\mathbf1[k=y]-p_k. This compares the correct class against other classes and a rejection alternative. J=10 is the program’s default teaching choice, not an asserted universal value. The paper contrasts competition with a correct-prototype-only objective that can collapse if all prototypes are allowed to adapt together. Shared weights receive the sum of gradients from every spatial use. Our program computes forward values and loss derivatives, not the whole training procedure. LeCun et al., 1998

A complete small program

Run with Python 3.12 and NumPy 1.26.4. The program implements every stage in the table. It uses random minus-one/plus-one prototypes rather than copying the paper’s seven-by-twelve character bitmaps. The paper describes those prototypes as initially fixed and also discusses learning them; our count excludes the 840 fixed entries explicitly. Initialization and the synthetic rectangular stroke are teaching choices, not the paper’s training data or preprocessing.

import numpy as np

C3 = tuple(tuple((start+j)%6 for j in range(3)) for start in range(6)) + \
     tuple(tuple((start+j)%6 for j in range(4)) for start in range(6)) + \
     ((0,1,3,4),(1,2,4,5),(0,2,3,5),tuple(range(6)))

def squash(x):
    return 1.7159*np.tanh((2/3)*x)

def conv_valid(image, weights, bias):
    a,w,b=np.asarray(image,dtype=float),np.asarray(weights,dtype=float),np.asarray(bias,dtype=float)
    if a.ndim!=3 or w.ndim!=4 or w.shape[2:]!=(5,5) or a.shape[2]!=w.shape[1] or b.shape!=(w.shape[0],):
        raise ValueError('need HWC image, OI55 weights and O bias')
    if min(a.shape[:2])<5 or min(w.shape)<1 or not all(np.isfinite(v).all() for v in (a,w,b)):
        raise ValueError('invalid convolution input')
    windows=np.lib.stride_tricks.sliding_window_view(a,(5,5),axis=(0,1))
    return np.einsum('hwcij,ocij->hwo',windows,w)+b

def subsample(image, scale, bias):
    a=np.asarray(image,dtype=float);scale=np.asarray(scale,dtype=float);bias=np.asarray(bias,dtype=float)
    if a.ndim!=3 or min(a.shape)<1 or a.shape[0]%2 or a.shape[1]%2 or scale.shape!=(a.shape[2],) or bias.shape!=scale.shape:
        raise ValueError('need even HWC dimensions and one scale/bias per channel')
    if not all(np.isfinite(v).all() for v in (a,scale,bias)):
        raise ValueError('subsampling values must be finite')
    summed=a.reshape(a.shape[0]//2,2,a.shape[1]//2,2,a.shape[2]).sum(axis=(1,3))
    return squash(summed*scale+bias)

def competitive_loss(distances, target, reject_cost=10.):
    d=np.asarray(distances,dtype=float)
    if d.ndim!=1 or not len(d) or not np.isfinite(d).all() or np.any(d<0):
        raise ValueError('finite nonnegative class distances required')
    if type(target) is not int or not 0<=target<len(d) or not np.isfinite(reject_cost) or reject_cost<=0:
        raise ValueError('valid target and positive reject cost required')
    logz=np.logaddexp.reduce(np.r_[-reject_cost,-d])
    gradient=-np.exp(-d-logz);gradient[target]+=1
    return float(d[target]+logz),gradient

def init_lenet(seed=11):
    rng=np.random.default_rng(seed)
    def weights(outgoing,incoming):
        return rng.normal(size=(outgoing,incoming,5,5))/np.sqrt(25*incoming)
    return dict(c1w=weights(6,1),c1b=np.zeros(6),s2a=np.full(6,.25),s2b=np.zeros(6),
                c3w=[weights(1,len(c)) for c in C3],c3b=np.zeros(16),
                s4a=np.full(16,.25),s4b=np.zeros(16),c5w=weights(120,16),c5b=np.zeros(120),
                f6w=rng.normal(size=(120,84))/np.sqrt(120),f6b=np.zeros(84),
                prototypes=rng.choice([-1.,1.],size=(10,84)))

def parameter_count(model):
    return sum(sum(a.size for a in v) if isinstance(v,list) else v.size
               for k,v in model.items() if k!='prototypes')

def forward(image, model):
    a=np.asarray(image,dtype=float)
    if a.shape!=(32,32,1) or not np.isfinite(a).all():
        raise ValueError('expected finite 32x32x1 input')
    trace=[]
    def record(name,x):
        trace.append((name,x.shape));return x
    a=record('C1',squash(conv_valid(a,model['c1w'],model['c1b'])))
    a=record('S2',subsample(a,model['s2a'],model['s2b']))
    a=record('C3',squash(np.concatenate([
        conv_valid(a[:,:,list(channels)],model['c3w'][i],model['c3b'][i:i+1])
        for i,channels in enumerate(C3)],axis=2)))
    a=record('S4',subsample(a,model['s4a'],model['s4b']))
    a=record('C5',squash(conv_valid(a,model['c5w'],model['c5b'])))
    a=record('F6',squash(a.ravel()@model['f6w']+model['f6b']))
    distances=record('RBF',((model['prototypes']-a)**2).sum(axis=1))
    return distances,trace

if __name__=='__main__':
    model=init_lenet();image=np.zeros((32,32,1));image[8:24,14:18,0]=1
    distances,trace=forward(image,model)
    print('trainable parameters excluding fixed codebook:',parameter_count(model))
    print('C3 connections:',sum(map(len,C3)),'C3 parameters:',sum(w.size for w in model['c3w'])+16)
    for name,shape in trace:print(name,shape)
    print('untrained RBF distances:',distances.round(4).tolist())
    print('zero input distances:',forward(np.zeros_like(image),model)[0].tolist())
    print('toy distance loss:',round(competitive_loss([1,2,3],1,4)[0],6))
trainable parameters excluding fixed codebook: 60000
C3 connections: 60 C3 parameters: 1516
C1 (28, 28, 6)
S2 (14, 14, 6)
C3 (10, 10, 16)
S4 (5, 5, 16)
C5 (1, 1, 120)
F6 (84,)
RBF (10,)
untrained RBF distances: [87.0858, 97.9977, 95.2155, 86.579, 77.0475, 96.6372, 95.2688, 101.1415, 93.7613, 92.1739]
zero input distances: [84.0, 84.0, 84.0, 84.0, 84.0, 84.0, 84.0, 84.0, 84.0, 84.0]
toy distance loss: 1.44019

The 60000 total counts free parameters, not every spatial connection or stored constant. The toy loss uses distances[1,2,3], target index 1 and rejection energy 4; it is separate from any proposed label for the untrained stroke image. The implementation uses logaddexp to avoid direct summation of tiny exponentials in the log normalizer.

Tests check the inspected C 3 table, exact stage counts, an independent literal multichannel convolution, learned subsampling, zero-input energies, the competitive-loss derivative by finite differences and invalid inputs. For a fixed architecture, each convolution costs O(HW times the number of connected kernel weights); subsampling is linear in its input size. This example fits comfortably on a CPU and provides no timing or accuracy comparison with the original system.

Limits and comparisons

The D 2 L teaching implementation uses sigmoid activations, nontrainable average pooling, dense map connections and a linear output layer. Those are legitimate teaching choices, but its class name does not make it identical to the 1998 architecture. D2L: LeNet

Changing the C 3 connection pattern, subsampling rule or output head changes the model. For example, remove the 44 learned subsampling parameters, connect C 3 fully instead of sparsely, and add an 84-to-10 linear head with bias: that specified variant has 61706 trainable parameters. The number follows from those choices; it is not a universal count for everything called LeNet.

Weight sharing reduces the number of independent parameters; it does not eliminate the computation at each position. Subsampling can lose a thin stroke or change alignment sensitivity. A small isolated-character network also does not solve page layout, segmentation, text sequencing or language-level error correction by itself. The 1998 paper concerns a larger document-recognition setting, of which this chapter examines a bounded component.

Exercises with answers

1. Why does C 3 have 1516 parameters rather than 16×6×25+16?

Answer. It has 60 connected map pairs rather than 96. Each pair contributes 25 weights and each output contributes one bias:60×25+16.

2. Set a subsampling coefficient to zero. What happens to its map?

Answer. Its output becomes the constant f(beta), regardless of the four input values. This cannot be described as fixed average pooling.

3. An RBF output is 84. Is that an 84% probability?

Answer. No. It is a squared distance. Zero features and an 84-entry plus/minus-one prototype produce 84; probabilities require a specified normalization and any rejection term.

4. Derive the 61706 count for the stated dense-head variant.

Answer. Start from 60000, remove 44 subsampling parameters, add 900 for dense C 3, then add 84×10+10=850 for the linear head. The result is 61706.

Sources and next steps

The primary source is a 46-page author-hosted scan, not the final journal pagination. We read the architecture and loss passages and visually checked the connection table, RBF/competitive-loss equations and activation constants. The full appendices and training results were not reproduced. D 2 L is used to compare an explicitly different teaching implementation. LeCun et al., 1998 D2L: LeNet

Review pooling and convolution, then compare AlexNet for changes in activation, compute organization and regularization.

Make a prediction, then check

With zero F 6 features and 84-entry ±1 prototypes, what is each RBF output?

Choose one answer

Learning objectives

  • Reconstruct sparse connectivity, learned subsampling and parameter counts.
  • Interpret distance energies and the competitive loss without confusing them with probabilities.

Prerequisites & connections

Explore related knowledge →

References

  1. Gradient-Based Learning Applied to Document Recognition — LeNet-5 method in author version
    Yann LeCun; Léon Bottou; Yoshua Bengio; Patrick Haffner · 1998
  2. Dive into Deep Learning 1.0.3 — lenet
    Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: bounded primary-source passages, explicit image classification experiments and CNN architecture models, executed programs, independent mathematical references, input boundaries and bilingual alignment. Not independent human or second-agent review; no full-system research reproduction claimed.

  • Single-agent authored technical review; runnable example, exact or literal reference checks, explicit assumptions and matching bilingual equations/exercises. Automated execution and rendering results recorded separately.
  • 9 tests: visually checked sparse C 3 table,60000 free parameters, full forward shapes, literal convolution, learned subsampling, squared-distance output, finite-difference competitive-loss gradient and invalid inputs. Page 9 loss and page 41 tanh constants visually checked. Random codebook is not the paper’s glyph codebook.
  • Single AI author compared both locales across six sections, assumptions, definitions, equations, executed code and output, four exercise/answer pairs and scoped citations.43 checks across six draft articles; not independent human review or full historical training reproduction.
  • Complete bilingual prose and corresponding exercises promoted with formal status and SHA binding. Algorithm tests read formal MDX; historical essays claim no executable program or computational tests.
  • After visual reading review, shortened/localized inline citation labels. Verified ordered link targets and every protected code/math/tag span unchanged; full source identities remain in metadata. Frozen drafts preserved and final article SHA rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.