Convolution
Convolution is a running weighted average: slide one signal across another, multiply, and add up. It describes the output of every linear time-invariant system, blurs images, smooths data, computes the distribution of a sum of random variables, and multiplies polynomials. This lesson defines it, computes it by hand and with NumPy, and lists its properties. The deep-learning view is in Math for Deep Learning: Convolution.
Definition
Read it as "flip , shift it to , multiply with , integrate". For finite sequences of lengths and , the full convolution has length .
import numpy as np
x = np.array([1, 2, 3])
h = np.array([1, 1, 1, 1])
print("np.convolve:", np.convolve(x, h).tolist())
# the same by the definition
y = [int(sum(x[k] * h[n - k] for k in range(len(x)) if 0 <= n - k < len(h))) for n in range(len(x) + len(h) - 1)]
print("by hand: ", y)
print("polynomial product (1 + 2z + 3z^2)(1 + z + z^2 + z^3):", np.polymul(x[::-1], h[::-1])[::-1].tolist())np.convolve: [1, 3, 6, 6, 5, 3]
by hand: [1, 3, 6, 6, 5, 3]
polynomial product (1 + 2z + 3z^2)(1 + z + z^2 + z^3): [1, 3, 6, 6, 5, 3]
Convolving coefficient lists multiplies polynomials. That is why the FFT also gives fast multiplication.
Smoothing and probability
Convolving data with a short kernel that sums to 1 is a weighted moving average. Convolving the probability distributions of two independent random variables gives the distribution of their sum:
import numpy as np
die = np.ones(6) / 6 # P(1..6)
two = np.convolve(die, die) # sums 2..12
print("P(sum of two dice), sums 2..12:", np.round(two * 36).astype(int).tolist(), "/ 36")
three = np.convolve(two, die)
print("most likely sums of three dice:", (np.argsort(three)[-2:] + 3).tolist(), " P =", round(three.max(), 4))
rng = np.random.default_rng(3)
signal = np.sin(np.linspace(0, 4 * np.pi, 50)) + 0.4 * rng.normal(size=50)
kernel = np.ones(5) / 5
smooth = np.convolve(signal, kernel, mode="same")
print("roughness (mean |diff|) before:", round(np.mean(np.abs(np.diff(signal))), 3), " after:", round(np.mean(np.abs(np.diff(smooth))), 3))P(sum of two dice), sums 2..12: [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1] / 36
most likely sums of three dice: [10, 11] P = 0.125
roughness (mean |diff|) before: 0.524 after: 0.16
Repeated convolution of the flat dice distribution heads toward a bell curve: the central limit theorem is a statement about convolution powers.
Properties
- Commutative , associative , distributive over addition.
- Identity: ; shift: .
- Widths add: if lives on an interval of length and on one of length , then lives on one of length .
- Smoothing: is at least as smooth as the smoother of the two. : two jumps convolve into a triangle with corners.
import numpy as np
dt = 0.001
box = np.ones(1000) # Pi on [-1/2, 1/2), sampled
tri = np.convolve(box, box) * dt # should be the triangle on [-1, 1]
t = (np.arange(tri.size) - (tri.size - 1) / 2) * dt
for tv in (-1.0, -0.5, 0.0, 0.25, 0.9):
i = int(round((tv - t[0]) / dt))
print(f"t={tv:5}: (box*box)(t) = {tri[i]:.3f} triangle 1-|t| = {max(1 - abs(tv), 0):.3f}")t= -1.0: (box*box)(t) = 0.001 triangle 1-|t| = 0.000
t= -0.5: (box*box)(t) = 0.500 triangle 1-|t| = 0.500
t= 0.0: (box*box)(t) = 1.000 triangle 1-|t| = 1.000
t= 0.25: (box*box)(t) = 0.750 triangle 1-|t| = 0.750
t= 0.9: (box*box)(t) = 0.100 triangle 1-|t| = 0.100
In software
np.convolve(x, h, mode)with"full","same"or"valid";scipy.signal.fftconvolveis much faster for long signals (Circular and Fast Convolution).- Deep-learning "convolution" layers actually compute cross-correlation (no flip); since the kernel is learned, the difference does not matter (Convolution in CNNs).
Exercises
Exercise 1: By hand
Compute .
Answer
.
Solution
, , , . Convolving with takes differences: it is a discrete derivative.
Exercise 2: Length
What is the length of the full convolution of a 1000-sample signal with a 31-tap filter?
Answer
Solution
. mode="same" trims it back to 1000, mode="valid" to .
Exercise 3: Sum of uniforms (code)
Use repeated convolution to find the distribution of the sum of four fair coins (0 or 1 each).
Answer
, the binomial coefficients.
Solution
import numpy as np
coin = np.array([0.5, 0.5])
d = coin
for _ in range(3):
d = np.convolve(d, coin)
print((d * 16).tolist())[1.0, 4.0, 6.0, 4.0, 1.0]
Convolving with itself repeatedly builds Pascal's triangle.
Test yourself
The full convolution of sequences of lengths 5 and 3 has length…
- 5
- 8
- 7
- 15
Convolving two coefficient lists computes…
- their sum
- the product of the polynomials
- their dot product
- their maximum
The convolution is…
- the triangle
- a Gaussian
- a delta