Search

Search papers and lessons

Convolution

Level 3 · 12 min read

Convolution slides a small set of weights along a signal, takes a weighted sum at each position, and so blends neighbouring values and picks out local patterns.

On this page

  • Colour = topic mix
  • Calculus
  • Architectures
  • Discrete math
  • Sign in to see your progress

TL;DR

Convolution combines two functions, or two lists of numbers, by sliding one over the other. At each position you multiply the overlapping values and add them up, then move on to the next position. The result is a smoothed or filtered version of the input, where each output value depends on its neighbours.

When one of the two inputs is a small pattern of weights (a kernel), convolution is a local detector: it responds strongly wherever the input looks like the pattern.

Where you'll see it: in image blur and edge detection, in audio filters and reverb, in the probability density of a sum of two independent random variables, and in the convolutional layers at the heart of image-recognition networks (convolutional neural networks).

Intuition

A moving window of weights

Take a noisy stream of temperature readings and replace each reading with the average of itself and its two neighbours. That is a moving average, and it is already a convolution. The window of weights is 13,13,13\frac{1}{3}, \frac{1}{3}, \frac{1}{3}. You slide it along the data, and at each place you take a weighted sum of what sits under it. Change the weights and you change the filter: give the centre more weight and you get a gentler smoothing, give the two neighbours opposite signs and you get a detector for change.

Why does this idea matter? Two reasons.

  1. Local structure is what most signals contain. A sharp edge in a photo, a note onset in a song and a sudden jump in a sensor all live in a few neighbouring values. A window of weights looks at exactly that size of thing.
  2. The same weights are reused everywhere. Sliding the window means one small set of numbers handles every position in the signal. That is far fewer parameters than a separate rule for each place, and it means a pattern is detected wherever it appears. This is a large part of why image networks work.

The plot below shows a step edge smeared by the moving average. Each output value is the average of three inputs, so the sharp jump becomes a ramp two positions wide.

0123450246810position nvalue
  • input signal
  • after 3-point average
The step at position 3 is spread over two positions by the moving average. The averaged values are 0, 3.33, 6.67 and 10.

The math

Definition for sequences

Definition: Discrete convolution

For two sequences ff and gg indexed by integers, their convolution is the sequence

(f∗g)[n]=∑k=−∞∞f[k] g[n−k].(f \ast g)[n] = \sum_{k=-\infty}^{\infty} f[k]\, g[n-k].

For finite sequences the sum runs only over the values that exist.

Here nn is the output position, and kk is a dummy index that runs over the input. The term g[n−k]g[n-k] is gg read backwards and shifted to nn. So the recipe is: flip gg, slide it to position nn, multiply the overlapping entries, and sum. The flip is the part that is easy to forget, and it is what makes convolution commutative: f∗g=g∗ff \ast g = g \ast f.

Definition for functions

For functions of a real variable the sum becomes an integral, which is why definite integrals are a prerequisite:

(f∗g)(t)=∫−∞∞f(τ) g(t−τ) dτ.(f \ast g)(t) = \int_{-\infty}^{\infty} f(\tau)\, g(t-\tau)\, d\tau.

The variable τ\tau plays the role of kk, and tt plays the role of nn.

Worked example in one dimension

Let f=[1,2,3]f = [1, 2, 3] and g=[0,1,0.5]g = [0, 1, 0.5], both starting at index 0. Only the terms where both indices are in range contribute, so the output has 3+3−1=53 + 3 - 1 = 5 entries.

(f∗g)[0]=f0g0=1⋅0=0(f∗g)[1]=f0g1+f1g0=1⋅1+2⋅0=1(f∗g)[2]=f0g2+f1g1+f2g0=1⋅0.5+2⋅1+3⋅0=2.5(f∗g)[3]=f1g2+f2g1=2⋅0.5+3⋅1=4(f∗g)[4]=f2g2=3⋅0.5=1.5\begin{aligned} (f \ast g)[0] &= f_0 g_0 = 1 \cdot 0 = 0 \\ (f \ast g)[1] &= f_0 g_1 + f_1 g_0 = 1 \cdot 1 + 2 \cdot 0 = 1 \\ (f \ast g)[2] &= f_0 g_2 + f_1 g_1 + f_2 g_0 = 1 \cdot 0.5 + 2 \cdot 1 + 3 \cdot 0 = 2.5 \\ (f \ast g)[3] &= f_1 g_2 + f_2 g_1 = 2 \cdot 0.5 + 3 \cdot 1 = 4 \\ (f \ast g)[4] &= f_2 g_2 = 3 \cdot 0.5 = 1.5 \end{aligned}

So f∗g=[0,1,2.5,4,1.5]f \ast g = [0, 1, 2.5, 4, 1.5]. As a check, the entries of ff sum to 6 and those of gg sum to 1.5, and 6×1.5=96 \times 1.5 = 9. The output entries also sum to 0+1+2.5+4+1.5=90 + 1 + 2.5 + 4 + 1.5 = 9. The total is always the product of the two sums.

Two dimensions and the image case

For an image II and a small kernel KK of size m×nm \times n, the 2D convolution is

(I∗K)[i,j]=∑a∑bI[i−a,j−b] K[a,b].(I \ast K)[i, j] = \sum_{a} \sum_{b} I[i-a, j-b]\, K[a, b].

Deep-learning libraries compute a slightly different operation called cross-correlation, which skips the flip:

(I⋆K)[i,j]=∑a∑bI[i+a,j+b] K[a,b].(I \star K)[i, j] = \sum_{a} \sum_{b} I[i+a, j+b]\, K[a, b].

Each output is the dot product of the kernel with the patch of the image under it. Since a network learns its kernels, flipping them or not makes no practical difference. Keep the two versions distinct when you read a textbook, though, because they differ by a sign in some examples.

Example
Edge detection on a 3 by 3 image

Take the image and the kernel

I=(120013210),K=(100−1).I = \begin{pmatrix} 1 & 2 & 0 \\ 0 & 1 & 3 \\ 2 & 1 & 0 \end{pmatrix}, \qquad K = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix}.

With no padding, the output is (3−2+1)×(3−2+1)=2×2(3-2+1) \times (3-2+1) = 2 \times 2. Each output value is I[i,j]−I[i+1,j+1]I[i,j] - I[i+1,j+1], computed with the cross-correlation form.

  1. Top-left: I[0,0]−I[1,1]=1−1=0I[0,0] - I[1,1] = 1 - 1 = 0.
  2. Top-right: I[0,1]−I[1,2]=2−3=−1I[0,1] - I[1,2] = 2 - 3 = -1.
  3. Bottom-left: I[1,0]−I[2,1]=0−1=−1I[1,0] - I[2,1] = 0 - 1 = -1.
  4. Bottom-right: I[1,1]−I[2,2]=1−0=1I[1,1] - I[2,2] = 1 - 0 = 1.

The output is (0−1−11)\begin{pmatrix} 0 & -1 \\ -1 & 1 \end{pmatrix}. Large magnitudes mark places where the image changes along the diagonal. The strict convolution would flip KK first, giving the output with the opposite sign everywhere, so the detected pattern is the same either way.

Example
A realistic blur kernel

A common 3 by 3 Gaussian-like blur kernel is

K=116(121242121).K = \frac{1}{16}\begin{pmatrix} 1 & 2 & 1 \\ 2 & 4 & 2 \\ 1 & 2 & 1 \end{pmatrix}.

Its entries sum to 16/16=116/16 = 1. Suppose a patch of the image is flat, every pixel value 10. Each output is 10×1=1010 \times 1 = 10, so a flat region stays flat and keeps its brightness. That is the defining property of a blur: the weights sum to 1, so the average level survives while sharp detail is softened. Near a sharp edge the centre pixels, which carry the most weight, pull the value towards their neighbours, so the edge is softened.

Output size with padding and stride

For an input of length nn, a kernel of length kk, padding pp (zeros added on each side) and stride ss (how far the window moves each step):

output length=⌊n+2p−ks⌋+1.\text{output length} = \left\lfloor \frac{n + 2p - k}{s} \right\rfloor + 1.

For n=3n = 3, k=2k = 2, p=0p = 0, s=1s = 1 this gives 22, which matches the edge example above.

Key properties

  • Commutative and associative: f∗g=g∗ff \ast g = g \ast f, and (f∗g)∗h=f∗(g∗h)(f \ast g) \ast h = f \ast (g \ast h).
  • Distributes over addition: f∗(g+h)=f∗g+f∗hf \ast (g + h) = f \ast g + f \ast h.
  • Identity: convolving with the unit impulse (1 at position 0, zero elsewhere) returns the input unchanged.
  • Convolution theorem: the Fourier transform (which re-expresses a signal as a sum of sine waves of different frequencies) of f∗gf \ast g is the pointwise product of the transforms of ff and gg. This is why filtering by convolution can be done as multiplication in the frequency domain, which is much faster for long signals.

Convolution of probability densities

If XX and YY are independent continuous random variables with densities pXp_X and pYp_Y, the density of their sum is the convolution of the two densities:

pX+Y(s)=∫pX(x) pY(s−x) dx.p_{X+Y}(s) = \int p_X(x)\, p_Y(s-x)\, dx.

Take XX and YY uniform on [0,1][0, 1]. For 0≤s≤10 \le s \le 1, the integrand is nonzero only where x∈[0,s]x \in [0, s], so the integral is ss. For 1≤s≤21 \le s \le 2, it is 2−s2 - s. The result is a triangle peaking at s=1s = 1 with height 1. The plot shows it.

−0.500.511.522.500.20.40.60.811.2sdensity
  • density of X + Y
Adding two uniform random values gives a triangular density. The peak at s = 1 has height 1, and the area under the triangle is 1.

The same rule explains why adding independent Gaussian variables gives another Gaussian: convolving two Gaussian densities produces a Gaussian whose variance is the sum of the two.

Worked examples

Example
Convolving two short sequences

Let f=[1,1,1]f = [1, 1, 1] (a three-point moving sum) and g=[1,2]g = [1, 2].

  1. Output length is 3+2−1=43 + 2 - 1 = 4.
  2. (f∗g)[0]=f0g0=1⋅1=1(f \ast g)[0] = f_0 g_0 = 1 \cdot 1 = 1.
  3. (f∗g)[1]=f0g1+f1g0=1⋅2+1⋅1=3(f \ast g)[1] = f_0 g_1 + f_1 g_0 = 1 \cdot 2 + 1 \cdot 1 = 3.
  4. (f∗g)[2]=f1g1+f2g0=1⋅2+1⋅1=3(f \ast g)[2] = f_1 g_1 + f_2 g_0 = 1 \cdot 2 + 1 \cdot 1 = 3.
  5. (f∗g)[3]=f2g1=1⋅2=2(f \ast g)[3] = f_2 g_1 = 1 \cdot 2 = 2.
  6. The result is [1,3,3,2][1, 3, 3, 2]. Its sum is 9, which is 3×33 \times 3, the product of the sums of the inputs.
Example
Stacking two box filters

Convolving the box filter [1/3,1/3,1/3][1/3, 1/3, 1/3] with itself gives [1/9,2/9,3/9,2/9,1/9][1/9, 2/9, 3/9, 2/9, 1/9].

  1. Each entry is a sum of products of 1/31/3 with 1/31/3. For example, the centre entry gets three pairs, each worth 1/91/9, so 3/93/9.
  2. The result is a wider, softer bump than one box filter. Repeated smoothing approaches a Gaussian shape, which is one face of the central limit theorem at work on a filter.

Tradeoffs and failure modes

Convolution is the right tool when the signal is local and the same pattern can occur anywhere. It is the wrong tool when it is not.

SituationProblemBetter choice
Patterns depend on absolute position (a face must be in a certain place)A local window cannot see global layoutAdd pooling, or position encodings, or fully connected layers
Long-range dependencies in a sequenceThe kernel only sees a few neighboursAttention, or dilated convolution to widen the window
Kernel sizes are largeDirect computation grows with the product of input and kernel sizesFFT-based convolution
Upsampling a feature mapOrdinary convolution only shrinks or keeps sizeTransposed Convolution

Some practical traps:

  • Border effects. Without padding, the output shrinks by k−1k - 1 each time you convolve. Stacking many layers with no padding can shrink a small image to nothing. Padding fixes the size but invents values at the border, usually zeros.
  • Checkerboard artefacts. Strided transposed convolutions can leave a regular pattern in the output when kernel size and stride do not divide evenly.
  • Sign and flip confusion. A library call named convolve may flip the kernel or not. Check which one you have before you hand-compute a result to compare against it.

History

The convolution integral appeared in analysis and probability long before it had a standard name; Laplace's work on sums of independent errors in the late 18th century already involves it. Its central idea, that the response of a linear system to an arbitrary input is a weighted sum of its responses to simple impulses, became the foundation of signal processing and linear systems theory in the 20th century.

In image processing, convolution with small kernels became standard in the 1960s and 1970s. The Sobel operator, a 3 by 3 kernel for finding edges, was presented by Irwin Sobel and Gary Feldman in the late 1960s, and it is a convolution. Such filters were hand-designed, and the people who used them knew what each kernel did.

The step that made convolution central to machine learning came in two stages. Kunihiko Fukushima's neocognitron in 1980 used layers of local, shared-weight feature detectors. In the late 1980s and 1990s Yann LeCun and his colleagues trained convolutional networks with backpropagation for handwritten digit recognition, and their 1998 LeNet-5 paper set the template that modern networks follow. The reason it caught on was the combination of local detection and weight sharing: a learned kernel can find the same feature anywhere, with far fewer parameters than a fully connected layer.

Check yourself

QuestionFor f=[2,0,1]f = [2, 0, 1] and g=[1,1]g = [1, 1], what is f∗gf \ast g?Show answer

Output length is 3+2−1=43 + 2 - 1 = 4. The entries are 2⋅1=22 \cdot 1 = 2, then 2⋅1+0⋅1=22 \cdot 1 + 0 \cdot 1 = 2, then 0⋅1+1⋅1=10 \cdot 1 + 1 \cdot 1 = 1, then 1⋅1=11 \cdot 1 = 1. The result is [2,2,1,1][2, 2, 1, 1]. Its sum is 6, which equals 3×23 \times 2, as it should.

QuestionWhy does the kernel get flipped in the textbook definition of convolution, and why do deep-learning libraries usually skip the flip?Show answer

The flip makes convolution commutative and makes it match the integral definition, where g(t−τ)g(t - \tau) reads gg backwards. Libraries skip it because the network learns its kernel weights anyway. Flipping a learned kernel just gives another kernel, so the flip changes nothing about what the model can represent.

QuestionA 5 by 5 image is convolved with a 3 by 3 kernel, no padding, stride 1. What is the output size, and what happens if you apply a second 3 by 3 convolution with no padding?Show answer

The first output is (5−3+1)×(5−3+1)=3×3(5-3+1) \times (5-3+1) = 3 \times 3. The second gives (3−3+1)×(3−3+1)=1×1(3-3+1) \times (3-3+1) = 1 \times 1. Two unpadded 3 by 3 layers shrink the image to a single pixel, which is why deep networks use padding.

QuestionYou add two independent random values, one uniform on [0,1][0, 1] and one uniform on [0,2][0, 2]. Why is the density of the sum the convolution of the two densities, and what is the probability that the sum is less than 1?Show answer

When two variables are independent, the probability of a given sum comes from integrating over every way the two can split it, and that integral is the convolution of the densities. For the probability, the sum is below 1 when the first value xx and second value yy satisfy x+y<1x + y \lt 1 with x∈[0,1]x \in [0,1] and y∈[0,2]y \in [0,2]. Since yy must be at least 0, the region is the triangle with corners (0,0)(0,0), (1,0)(1,0) and (0,1)(0,1) in the (x,y)(x, y) plane, which has area 12\frac{1}{2}. The joint density is 12\frac{1}{2} on the rectangle [0,1]×[0,2][0,1] \times [0,2], so the probability is 12⋅12=14\frac{1}{2} \cdot \frac{1}{2} = \frac{1}{4}.

Sources