Lesson 6.1Module 6: Autocorrelation and forecasting45 minIntermediate
Autocorrelation: finding the beat
Compare a series with a shifted copy of itself and repetition jumps out. Use autocorrelation to find the pitch of a note, the tempo of a drum loop and the yearly rhythm of streaming, and see why tempo trackers so often get the speed doubled.
How does an app tell you a song is 100 beats per minute, or that you're singing a G? Neither app understands music. Each slides the signal along a copy of itself and looks for the shift at which the two line up. That shift is the period, and the measure of "lining up" is the autocorrelation you met in lesson 4.2. This lesson puts it to work on three timescales: thousandths of a second (pitch), fractions of a second (the beat), and days (the yearly rhythm of listening).
Set up
You need data.csv from the Spotify dataset (lesson 2.1) and christmas_pageviews.csv (lesson 2.2). The audio in this lesson is simulated, so you can check every answer against the truth.
import wave
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.stattools import acf
SR = 22050 # samples per second
rng = np.random.default_rng(3)
def save_wav(name, x, sr=SR):
"""Save a numpy array as a 16-bit mono WAV file you can play (from lesson 1.2)."""
x = x / np.max(np.abs(x))
pcm = (x * 0.8 * 32767).astype(np.int16)
with wave.open(name, "wb") as f:
f.setnchannels(1)
f.setsampwidth(2)
f.setframerate(sr)
f.writeframes(pcm.tobytes())Autocorrelation, by hand
The autocorrelation at lag k is the correlation between the series and the same series shifted k steps. Take away the mean, multiply each value by the value k steps later, add up, and divide by the same sum at lag 0 so the answer lies between −1 and 1:
r(k) = Σ (xₜ − x̄)(xₜ₊ₖ − x̄) / Σ (xₜ − x̄)²
When the series repeats every P steps, a copy shifted by P lies on top of the original, so r(P) is high. That's the whole trick. Here it is written out, checked against statsmodels:
def autocorr(x, k):
d = x - x.mean()
return np.sum(d[:-k] * d[k:]) / np.sum(d * d)
x = rng.normal(size=500)
print(f"By hand: {autocorr(x, 3):.4f} statsmodels: {acf(x, nlags=3)[3]:.4f}")The two agree. From here on we use acf(..., fft=True), which gets the same numbers much faster for long series by going through the spectrum from lesson 4.2. The autocorrelation and the spectrum are two views of the same information, a result named after Norbert Wiener (1930) and Aleksandr Khinchin (1934).
Timescale 1: the pitch of a note
A sung or played note is a wave that repeats. Its fundamental frequency (the pitch you hear) is the number of repeats per second. Let's make a G3 note, 196 Hz, with eight harmonics (whole-number multiples of 196 Hz) so it sounds more like an instrument than a pure tone:
f0 = 196.0 # G below middle C
t = np.arange(int(0.5 * SR)) / SR
note = sum(np.sin(2 * np.pi * h * f0 * t) / h for h in range(1, 9)) * np.exp(-3 * t)
save_wav("note.wav", note)
r = acf(note, nlags=400, fft=True)
min_lag = SR // 1000 # ignore shifts under 1 ms (pitches above 1000 Hz)
P = min_lag + np.argmax(r[min_lag:])
print(f"Best lag: {P} samples = {1000 * P / SR:.2f} ms, so pitch = {SR / P:.1f} Hz")
# The true period, 22050 / 196 = 112.5 samples, falls between two lags.
# Fit a parabola through the peak and its neighbours to find the top between them.
a, b, c = r[P - 1], r[P], r[P + 1]
P_fine = P + 0.5 * (a - c) / (a - 2 * b + c)
print(f"Refined lag: {P_fine:.2f} samples, so pitch = {SR / P_fine:.1f} Hz")
fig, axes = plt.subplots(2, 1, figsize=(10, 5))
ms = 1000 * np.arange(len(t)) / SR
axes[0].plot(ms[:600], note[:600])
axes[0].set_title("The note: about five repeats in 25 ms", loc="left")
axes[0].set_xlabel("Time (ms)")
lag_ms = 1000 * np.arange(len(r)) / SR
axes[1].plot(lag_ms, r)
axes[1].axvline(1000 * P / SR, color="C1", linestyle="--")
axes[1].annotate(f"peak at {1000 * P / SR:.2f} ms", (1000 * P / SR, r[P]),
xytext=(8, -14), textcoords="offset points", color="C1")
axes[1].set_title("Autocorrelation of the note", loc="left")
axes[1].set_xlabel("Lag (ms)")
plt.tight_layout()
plt.show()The best whole-number lag is 112 samples (5.08 ms), which gives 196.9 Hz. The parabola through the peak and its two neighbours puts the top at 112.5 samples, and the pitch at exactly 196.0 Hz. Tuner apps use this idea. A refined version called YIN (de Cheveigné and Kawahara, 2002) is one of the most widely used pitch detectors.
Notice the peaks at 2 and 3 times the period too. A wave that repeats every 5 ms also repeats every 10 ms and every 15 ms. Choosing the wrong one of these gives a pitch an octave (or more) too low, a classic pitch-tracker mistake. Here the first peak is the highest, so the right answer wins. Hold that thought: on drums it won't.
Timescale 2: the beat of a drum loop
Now a simulated drum loop: 100 beats per minute (BPM), kick drum on beats 1 and 3, snare on 2 and 4, and a hi-hat on every half-beat. A human drummer is never perfectly on time, so each hit is nudged by a random few milliseconds. We'll want more than one drummer later, so the loop is made by a function.
BPM = 100
beat = 60 / BPM # 0.6 seconds per beat
def make_drums(rng, bpm=BPM, jitter=0.008, n_beats=24):
"""A simulated drum loop: n_beats beats (24 = 6 bars of 4), timing error of about `jitter` seconds."""
beat = 60 / bpm
n = int(SR * (beat * n_beats + 1))
x = np.zeros(n)
def hit(kind, at):
i = max(int(at * SR), 0) # a hit can't start before the recording
tt = np.arange(int(0.25 * SR)) / SR
if kind == "kick": # low thump with a falling pitch
s = np.sin(2 * np.pi * (55 + 90 * np.exp(-30 * tt)) * tt) * np.exp(-12 * tt)
elif kind == "snare": # noise burst plus a tone
s = (0.6 * rng.normal(size=len(tt)) + 0.4 * np.sin(2 * np.pi * 190 * tt)) * np.exp(-20 * tt)
else: # hi-hat: a short, quiet tick of noise
tt = tt[:int(0.05 * SR)]
s = 0.25 * rng.normal(size=len(tt)) * np.exp(-80 * tt)
x[i:i + len(s)] += s[:n - i]
for b in range(n_beats):
at = b * beat + rng.normal(0, jitter)
hit("kick" if b % 4 in (0, 2) else "snare", at)
hit("hat", at)
hit("hat", at + beat / 2 + rng.normal(0, jitter))
return x + rng.normal(0, 0.01, n) # a little background hiss
drums = make_drums(rng)
save_wav("drums.wav", drums)Autocorrelating the raw waveform would find the pitch of the drums, not the beat, since the waveform's repeats are thousandths of a second long. What repeats at the beat is the pattern of hits. So first turn the audio into an onset envelope, a series that jumps whenever a sound starts:
- Cut the audio into frames of 441 samples (20 ms, so 50 frames per second).
- Measure the energy (sum of squares) in each frame, and take its log, because the ear hears loudness on a log scale (decibels are logs).
- Keep only the increases in log energy from one frame to the next. A hit is a sudden increase; the decay that follows doesn't matter.
HOP = 441
FPS = SR / HOP # 50 frames per second
def onset_envelope(x):
frames = len(x) // HOP
energy = (x[:frames * HOP].reshape(frames, HOP) ** 2).sum(axis=1)
return np.maximum(np.diff(np.log(energy + 1e-6)), 0)
onset = onset_envelope(drums)
fig, axes = plt.subplots(2, 1, figsize=(10, 4.6), sharex=True)
secs = np.arange(len(drums)) / SR
two_bars = secs < 8 * beat
axes[0].plot(secs[two_bars], drums[two_bars], linewidth=0.5)
axes[0].set_title("Two bars of the drum loop", loc="left")
frame_secs = np.arange(1, len(onset) + 1) / FPS
axes[1].plot(frame_secs[frame_secs < 8 * beat], onset[frame_secs < 8 * beat], color="C1")
axes[1].set_title("Onset envelope: a spike at every hit", loc="left")
axes[1].set_xlabel("Time (seconds)")
plt.tight_layout()
plt.show()Now autocorrelate the onset envelope, for lags up to 4 seconds. A lag of L frames is L/50 seconds, which corresponds to a tempo of 60 × 50 / L BPM.
lags = np.arange(201)
tempo_at = 60 * FPS / np.maximum(lags, 1) # the tempo each lag stands for
SHORTEST = 10 # ignore lags under 0.2 s (over 300 BPM)
def best_tempo(r, weight=1.0):
return tempo_at[SHORTEST + np.argmax((r * weight)[SHORTEST:])]
r = acf(onset, nlags=200, fft=True)
print(f"Highest peak: {best_tempo(r):.0f} BPM")
for L in sorted(np.argsort(r[SHORTEST:])[::-1][:5] + SHORTEST):
print(f" lag {L / FPS:.2f} s -> {tempo_at[L]:5.0f} BPM r = {r[L]:.2f}")The highest peak is at 0.6 seconds: the right answer, 100 BPM (r = 0.65). But the runner-up, not far behind at r = 0.56, is 0.3 seconds: 200 BPM, twice the true tempo. The other big peaks are all at multiples of the half-beat.
The loop really does repeat every 0.3 seconds: the hi-hats tick on every half-beat, so a half-beat shift lines hits up with hits too. Only the sizes of the hits differ, so the 0.6-second peak wins by a small margin, and a different drummer might tip it the other way. Let's try 200 drummers, each with their own random timing:
picks = [best_tempo(acf(onset_envelope(make_drums(np.random.default_rng(s))), nlags=200, fft=True))
for s in range(200)]
print(f"Drummers whose loop's highest peak is 200 BPM: {np.mean(np.isclose(picks, 200)):.0%}")For 56% of the drummers, the highest peak is double time. Our first drummer happened to be among the other 44%. This is the octave error: tempo trackers famously report double or half the tempo a person would tap. The autocorrelation isn't wrong, because the loop does repeat at both lags. The hard part is deciding which repeat a listener would call "the beat". It's the drum version of the pitch problem above, but here the wrong answer wins more often than not.
Real tempo trackers break the tie with a prior (a preference set before seeing the data): most music is felt somewhere around 120 BPM, so weight each lag by how plausible its tempo is. Dan Ellis's beat tracker (2007) uses a weighting like this one, a bell curve on a log scale centred on 120 BPM:
weight = np.exp(-0.5 * np.log2(tempo_at / 120) ** 2)
print(f"Weight at 100 BPM: {weight[30]:.2f} at 200 BPM: {weight[15]:.2f}")
picks_w = [best_tempo(acf(onset_envelope(make_drums(np.random.default_rng(s))), nlags=200, fft=True), weight)
for s in range(200)]
print(f"With the weighting, drummers called at 100 BPM: {np.mean(np.isclose(picks_w, 100)):.0%}")
fig, ax = plt.subplots(figsize=(10, 3.6))
ax.plot(lags / FPS, r, label="autocorrelation")
ax.plot(lags / FPS, r * weight, label="weighted by the 120 BPM prior", color="C3")
for L, side in [(15, "right"), (30, "left")]:
ax.axvline(L / FPS, color="grey", linestyle=":")
ax.annotate(f"{tempo_at[L]:.0f} BPM", (L / FPS, 0.9), xytext=(-5 if side == "right" else 5, 0),
textcoords="offset points", ha=side)
ax.set_xlim(0, 4)
ax.set_title("Autocorrelation of the onset envelope (first drummer)", loc="left")
ax.set_xlabel("Lag (seconds)")
ax.legend(loc="upper right")
plt.show()The prior keeps 0.97 of the 100 BPM peak but only 0.76 of the 200 BPM peak. That's enough to call 80% of the drummers correctly at 100 BPM. The other 20% are still called at double time: for them the half-beat peak was so much higher that even the discount couldn't overturn it. So a prior helps a lot, but it isn't a cure. Real trackers add more evidence, for instance checking whether there are also peaks at 2, 3 and 4 times the candidate lag, as a true beat should have, and in the end some songs are genuinely ambiguous: two listeners can tap the same track at different speeds and both be right. Don't take my word for it: listen. These lines add a click track at each tempo on top of the loop:
def with_clicks(bpm):
out = drums.copy()
click = np.sin(2 * np.pi * 1500 * np.arange(int(0.02 * SR)) / SR) * 0.8
for at in np.arange(0, len(drums) / SR - 0.05, 60 / bpm):
i = int(at * SR)
out[i:i + len(click)] += click
return out
save_wav("clicks_200.wav", with_clicks(200))
save_wav("clicks_100.wav", with_clicks(100))Both click tracks sit on the beat (the loop starts on a beat, so the clicks start at time 0). Neither is "wrong" the way a 137 BPM click would be, drifting in and out of time. But play them: the 100 BPM clicks are the ones you'd nod along to, while the 200 BPM clicks feel frantic.
Octave errors in a real dataset
The tempo column in the Spotify file was produced by an automatic tracker (Spotify inherited it from The Echo Nest, and its exact method isn't public), so does it show the octave problem? Let's look at the spread of tempos. (Lesson 5.1 found 143 tracks with a tempo of 0, a failed analysis, so drop those first.)
tracks = pd.read_csv("data.csv", usecols=["tempo"])
tempo = tracks["tempo"].replace(0, np.nan).dropna()
counts, edges = np.histogram(tempo, bins=np.arange(40, 230, 5))
for lo, c in zip(edges[:-1], counts):
if lo in (80, 90, 120, 150, 160, 170, 200):
print(f"{lo:.0f}-{lo + 5:.0f} BPM: {c:6,} tracks")
fig, ax = plt.subplots(figsize=(10, 3.4))
ax.bar(edges[:-1], counts, width=4.5, align="edge")
ax.set_title("Tempo of 170,510 tracks, as measured by Spotify's analyser", loc="left")
ax.set_xlabel("Tempo (BPM)")
ax.set_ylabel("Tracks")
plt.show()Most tracks are between 75 and 140 BPM, with a broad top from about 95 to 130 BPM. The counts then fall to a low of 2,618 tracks at 160–165 BPM, and rise again, to 3,768 at 170–175 BPM. A second hump at roughly twice the tempo of the 80–90 BPM crowd is what you'd expect if some slower songs were measured in double time, like our drum loop before weighting. Some of the tracks in that hump really are fast (punk, drum and bass), so we can't tell from this chart which individual readings are wrong. But it's a warning: an automated tempo of 170 might be a song you'd tap at 85. If you use tempo in a model, consider folding readings into a single octave, say 70–140 BPM, by halving anything above 140.
Timescale 3: the rhythm of a year
The same tool works on days instead of milliseconds. Here's the autocorrelation of daily (log) views of the Wikipedia page for Mariah Carey's All I Want for Christmas Is You (lesson 2.2), for lags up to 800 days:
pv = pd.read_csv("christmas_pageviews.csv", parse_dates=["date"], index_col="date")["views"]
log_views = np.log(pv.asfreq("D"))
print(f"{len(log_views):,} days, {log_views.isna().sum()} missing")
r_days = acf(log_views, nlags=800, fft=True)
for k in (7, 30, 182, 365, 730):
print(f"lag {k:3d} days: r = {r_days[k]:.2f}")
fig, ax = plt.subplots(figsize=(10, 3.4))
ax.plot(r_days)
for k in (182, 365, 730):
ax.axvline(k, color="grey", linestyle=":")
ax.axhline(0, color="grey", linewidth=0.8)
ax.set_title("Autocorrelation of daily views of 'All I Want for Christmas Is You' (log)", loc="left")
ax.set_xlabel("Lag (days)")
plt.show()The beat of this series is one year. Shift it by 365 days and it lines up with itself almost as well as shifting by a week (0.85 against 0.92). Shift it by half a year and you match December against June, and the autocorrelation goes negative (−0.29). The second peak, at 730 days, is a little lower (0.74), because the page's level drifts over the decade.
The weekly rhythm that lesson 4.4 found (weekend views about 3% higher) is there too, but it's far too small to see on this chart. A ±3% wiggle is swamped by a yearly cycle in which December views are many times June's. Autocorrelation finds the strongest repetition. To find weaker ones, first remove the strong one, for example by working with the seasonally adjusted series from lesson 4.3.
Key ideas
- Autocorrelation compares a series with a copy of itself shifted by a lag. A series that repeats every P steps has a peak at lag P.
- The same method finds the pitch of a note (lags of milliseconds), the tempo of music (fractions of a second) and the season of a streaming series (days).
- For tempo, autocorrelate an onset envelope (the rises in log energy), not the raw waveform.
- A repeat at P is also a repeat at 2*P*, 3*P* and so on, and some patterns repeat at P/2 as well. Choosing the wrong peak is the octave error. A prior around 120 BPM fixes most cases, but not all.
- Automated tempo data probably contains octave errors: Spotify's tempos have a suspicious second hump near 170 BPM.
- Autocorrelation shows the strongest repetition first. Remove it to see weaker ones.
Try it yourself
- Change
BPMto 128 (a typical house-music tempo). Does the unweighted autocorrelation still choose double time? What about the weighted one? - Remove the hi-hats from the drum loop. Which peak is highest now, and why?
- Increase the drummer's timing error from 0.008 to 0.03 seconds. What happens to the height of the peaks at long lags, and why does a sloppy drummer make the bar harder to find than the beat?
- Using the Spotify file, fold every tempo above 140 BPM into the 70–140 range by halving it, and redraw the histogram. Does the second hump disappear? Is anything lost by doing this?
Next lesson: Partial autocorrelation and lag plots
The course
Music as Data: Time Series with Python
1Music as a time series
2Seeing patterns
3Decomposition and stationarity
4Testing a time series
5Missing values
6Autocorrelation and forecasting
7Smoothing and Granger causality
8From time series to AI music