AI Wiki中文/EN

Convolution

卷积

Scan positions with shared local weights and understand parameter sharing, output shapes, and translation equivariance.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Intuition: local patterns can occur anywhere

An edge can appear in any corner of an image. Learning a separate detector at every location wastes parameters and ignores image structure. A convolutional layer reuses a small kernel across positions: multiply corresponding elements of a local window and the kernel, then sum them to produce a response.

Machine-learning frameworks usually perform cross-correlation, without the kernel reversal in the strict mathematical definition of convolution. A learned kernel can still represent the necessary pattern, but hand calculations and comparisons with signal-processing formulas must use a consistent convention. D2L: convolutions for images

The operation and its output shape

For one channel, no padding, and unit stride:

Yi,j=∑u=0kh−1∑v=0kw−1Ku,vXi+u,j+v+b.Y_{i,j}=\sum_{u=0}^{k_h-1}\sum_{v=0}^{k_w-1}K_{u,v}X_{i+u,j+v}+b.

The general output-height formula is:

Hout=⌊H+2p−d(k−1)−1s⌋+1.H_{out}=\left\lfloor\frac{H+2p-d(k-1)-1}{s}\right\rfloor+1.

pp is equal padding on each side, dd the dilation, and ss the stride. Width follows the same rule. A multi-channel layer also sums across input channels, with a separate kernel group for each output channel. Parameter count is CoutCinkhkw+CoutC_{out}C_{in}k_hk_w+C_{out}, independent of image height and width, while computation grows with output area. D2L, padding and stride

Sharing parameters encodes translation equivariance: shifting an input shifts its responses. Boundary handling, strided subsampling, and other modules limit this property. Equivariance is not invariance. A classifier needs aggregation or learned mechanisms for its final category to ignore some positional changes.

For the shape formula, all dimensions, stride and dilation are positive integers, padding is a nonnegative integer, and the effective kernel must fit inside the padded input. A dilated width-kk kernel spans d(k−1)+1d(k-1)+1 input positions. Valid starting offsets are 0,s,2s,…0,s,2s,\ldots up to H+2p−[d(k−1)+1]H+2p-[d(k-1)+1], which gives the floor formula. The parameter count above assumes a standard ungrouped layer with one bias per output channel; grouped and depthwise layers use different counts.

As a numerical check, height 7, kernel 3, dilation 2, padding 1 and stride 2 give effective kernel 5 and output height 3. Stride greater than one usually preserves shifts only on a compatible sampling lattice, and finite padding changes boundary responses. Parameter sharing alone does not make the final classification invariant.

Cross-correlation you can check by hand

import math

def shape(matrix):
    if not matrix or not matrix[0]:
        raise ValueError("nonempty matrix required")
    width = len(matrix[0])
    if any(len(row) != width for row in matrix):
        raise ValueError("rectangular matrix required")
    if any(not math.isfinite(x) for row in matrix for x in row):
        raise ValueError("finite entries required")
    return len(matrix),width

def output_size(length, kernel, padding=0, stride=1, dilation=1):
    if any(type(x) is not int for x in (length,kernel,padding,stride,dilation)):
        raise ValueError("integer dimensions required")
    if min(length,kernel,stride,dilation) < 1 or padding < 0:
        raise ValueError("invalid dimensions")
    effective = dilation*(kernel-1)+1
    if effective > length+2*padding:
        raise ValueError("effective kernel exceeds padded input")
    return (length+2*padding-effective)//stride+1

def correlate2d(image,kernel):
    height,width = shape(image)
    kh,kw = shape(kernel)
    oh,ow = output_size(height,kh),output_size(width,kw)
    result = [[sum(image[i+u][j+v]*kernel[u][v]
                   for u in range(kh) for v in range(kw))
               for j in range(ow)] for i in range(oh)]
    if any(not math.isfinite(x) for row in result for x in row):
        raise ArithmeticError("nonfinite correlation")
    return result

x = [[1,2,3],[4,5,6],[7,8,9]]
k = [[1,0],[0,-1]]
assert correlate2d(x,k) == [[-4,-4],[-4,-4]]
assert output_size(5,3) == 3
assert output_size(7,3,padding=1,stride=2,dilation=2) == 3
assert correlate2d([[2]],[[3]]) == [[6]]
assert correlate2d([[1,3,8]],[[1,-1]]) == [[-2,-5]]
assert correlate2d([[1,3,8]],[[-1,1]]) == [[2,5]]
for bad in [[],[[]],[[1],[2,3]],[[float('nan')]]]:
    try:
        correlate2d(bad,[[1]])
    except ValueError:
        pass
    else:
        raise AssertionError("invalid matrix accepted")

The implementation validates nonempty rectangular finite arrays and demonstrates single-channel valid cross-correlation without a bias. Its separate shape helper checks padding, stride, and dilation sizes; it does not apply those options to the correlation function. Direct correlation costs O(H_out W_out k_h k_w) operations and stores O(H_out W_out) outputs. Real layers add batches, channels, biases, and trainable weights.

Limitations and misconceptions

A local kernel does not directly connect arbitrary distant pixels in one layer. Stacking layers expands the receptive field, but its theoretical extent differs from the strength of actual influence. Convolution does not automatically handle arbitrary rotations, scale changes, or distribution shifts.

An edge-detection visualization does not prove that an entire network decides only from edges. Deeper representations, objectives, and the prediction head affect its behavior. A model may still exploit background textures or other shortcuts.

Experiments and exercises

  1. What is the output of a 5×5 input with a 3×3 kernel, no padding, and unit stride? Answer: 3×3.
  2. How many parameters for 3 input channels, 8 output channels, 3×3 kernels, and biases? Answer: 8×3×3×3+8=2248\times3\times3\times3+8=224.
  3. Does doubling image width and height double parameter count? Answer: no, though it generally increases computation.
  4. Apply [1,−1] to [1,3,8] without reversal. Answer: responses are [−2,−5]. Reversing the kernel gives [2,5], demonstrating why convolution and cross-correlation conventions must be distinguished. Then compare edge, mean, and sharpening kernels in the experiment.

Research connections

Pooling changes spatial resolution; residual connections affect deep-network training; depthwise separable convolution reduces the cost of some convolution operations. Vision Transformers organize image information through another architecture. When exploring CNN Explainer, follow channel counts and shapes through the layers rather than focusing only on the final label.

Make a prediction, then check

For a 5×5 input, 3×3 kernel, stride 1, and no padding, what is the output size?

Choose one answer

Learning objectives

  • Distinguish mathematical convolution from common neural-network cross-correlation.
  • Calculate a small kernel output and track shapes and boundaries.

Prerequisites & connections

Explore related knowledge →

References

  1. Convolutions for Images
    D2L authors
  2. Dive into Deep Learning — Padding and Stride
    Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola · 2023
  3. CNN Explainer
    Polo Club, Georgia Tech

Version2 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.

  • Independently enumerated valid window starts for 648 size, padding, stride, and dilation settings, checking shape or rejection; recomputed asymmetric-kernel and reversed responses.
  • Checked the ungrouped assumption behind 224 parameters, boundary equivariance limits, and the distinction between the shape helper and correlation function.
  • Compared the main claims, assumptions, examples, exercises, and citations across languages; structural checks additionally compare display equations, code, and source IDs. This is an AI technical check, not independent human peer review.

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.