Lesson 6.2Module 6: Autocorrelation and forecasting45 minIntermediate

Partial autocorrelation and lag plots

Autocorrelation mixes direct and inherited memory. Partial autocorrelation separates them, which is how forecasters choose a model. Then lag plots show the patterns that both measures miss, including a melody with no autocorrelation that is completely predictable.

Part of the free course Music as Data: Time Series with Python · taught by Terence D. Agbeyegbe and Tone Agbeyegbe

Lesson 6.1 used autocorrelation to find repetition. But autocorrelation has a blind spot: if this year depends on last year, and last year depended on the year before, then this year is correlated with two years ago too, even though there's no direct link. Partial autocorrelation strips out that inherited part. Together, the two measures are how forecasters pick a model, an approach set out by George Box and Gwilym Jenkins (1970). And when both measures say "nothing here", a simple scatter plot called a lag plot can still reveal a pattern.

Set up

You need data_by_year.csv and data.csv from the Spotify dataset (lesson 2.1) and christmas_pageviews.csv (lesson 2.2). Series labelled "simulated" are made up, so we know the right answer.

Python
import wave

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.stattools import acf, pacf
from statsmodels.stats.diagnostic import acorr_ljungbox

rng = np.random.default_rng(1)
SR = 22050


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())


def bars(ax, values, n, title):
    """Bar chart of autocorrelations (lags 1 onwards) with the ±1.96/√n band from lesson 4.2."""
    band = 1.96 / np.sqrt(n)
    lags = np.arange(1, len(values) + 1)
    ax.bar(lags, values, color=["C1" if abs(v) > band else "C0" for v in values])
    ax.axhspan(-band, band, color="grey", alpha=0.2)
    ax.axhline(0, color="grey", linewidth=0.8)
    ax.set_ylim(-1.05, 1.05)
    ax.set_title(title, fontsize=9, loc="left")


def ar(phis, n, burn=200):
    """Simulate an autoregression: x_t = phi_1 x_(t-1) + phi_2 x_(t-2) + ... + new noise."""
    e = rng.normal(size=n + burn)
    x = np.zeros(n + burn)
    for t in range(len(phis), n + burn):
        x[t] = sum(p * x[t - k - 1] for k, p in enumerate(phis)) + e[t]
    return x[burn:]                                # drop the start, before the series settles

Inherited memory

Take the simplest series with memory, from lesson 4.2: each value is 0.8 times the previous one plus fresh noise. This is an autoregression of order 1, or AR(1), because it looks back one step. Today depends directly on yesterday only. Yet:

Python
x = ar([0.8], 2000)
r = acf(x, nlags=3)
print(f"Lag 1: {r[1]:.2f}   lag 2: {r[2]:.2f}   lag 3: {r[3]:.2f}")

The lag-2 autocorrelation is about 0.64, which is 0.8 × 0.8. Two days ago affects today only through yesterday, but the autocorrelation can't tell that apart from a direct link. It counts the inherited memory as well as the direct memory.

Fingerprints: reading the two charts together

Box and Jenkins's insight was that common kinds of series leave different fingerprints on the two charts. Here are three simulated series, each 500 steps long:

  • AR(1): each value is 0.8 times the last plus noise.
  • AR(2): each value depends on the last two: 1.2 times the last, minus 0.6 times the one before. Pushing one way and pulling back the other makes the series swing up and down in rough cycles.
  • MA(1), a moving average of order 1: each value is today's noise plus 0.8 times yesterday's noise. A shock lasts exactly two steps, then is forgotten. (This "moving average" is a model, not the smoothing average of lesson 3.1. The shared name is a historical accident.)
Python
n = 500
e = rng.normal(size=n + 1)
series = {
    "AR(1), simulated": ar([0.8], n),
    "AR(2), simulated": ar([1.2, -0.6], n),
    "MA(1), simulated": e[1:] + 0.8 * e[:-1],
}

fig, axes = plt.subplots(3, 2, figsize=(10, 7), sharex=True)
for row, (name, s) in zip(axes, series.items()):
    bars(row[0], acf(s, nlags=15)[1:], n, f"{name}: autocorrelation")
    bars(row[1], pacf(s, nlags=15, method="ols")[1:], n, f"{name}: partial autocorrelation")
axes[2, 0].set_xlabel("Lag")
axes[2, 1].set_xlabel("Lag")
plt.tight_layout()
plt.show()
Six bar charts in three rows. AR(1): the autocorrelation declines gradually from about 0.8; the partial autocorrelation has one tall bar at lag 1 and nothing after. AR(2): the autocorrelation swings, positive then negative then positive, shrinking; the partial autocorrelation has two bars, positive at lag 1 and negative at lag 2, then nothing. MA(1): the autocorrelation has one bar at lag 1 and nothing after; the partial autocorrelation swings between positive and negative and fades out gradually.
Six bar charts in three rows. AR(1): the autocorrelation declines gradually from about 0.8; the partial autocorrelation has one tall bar at lag 1 and nothing after. AR(2): the autocorrelation swings, positive then negative then positive, shrinking; the partial autocorrelation has two bars, positive at lag 1 and negative at lag 2, then nothing. MA(1): the autocorrelation has one bar at lag 1 and nothing after; the partial autocorrelation swings between positive and negative and fades out gradually.

Read each row across:

  • AR(1): the autocorrelation fades gradually; the partial autocorrelation cuts off after lag 1.
  • AR(2): the autocorrelation fades in a wave, because of the cycles; the partial autocorrelation cuts off after lag 2. The order of an AR model is where the partial chart cuts off.
  • MA(1): the mirror image. The autocorrelation cuts off after lag 1, because a shock is forgotten after one step. The partial autocorrelation fades gradually.

So the rule of thumb is: a cut-off in the partial chart says AR; a cut-off in the ordinary chart says MA. The position of the cut-off gives the order. Lesson 6.3 and Module 7 build forecasts on this.

An AR(2) you can hear

The AR(2) above swings in rough cycles. Make the cycles fast enough and you can hear them. Run white noise, the hiss from lesson 4.2, through an AR(2) at audio rate, with its two numbers chosen to make it swing 440 times a second:

  • φ₁ = 2 × 0.995 × cos(2π × 440 / 22050)
  • φ₂ = −0.995²

Here 0.995 sets how long each swing rings on: the closer to 1, the purer the tone.

Python
f, ring = 440, 0.995
phi1, phi2 = 2 * ring * np.cos(2 * np.pi * f / SR), -ring ** 2
print(f"phi1 = {phi1:.4f}, phi2 = {phi2:.4f}")

hiss = rng.normal(size=2 * SR)
whistle = np.zeros_like(hiss)
for t in range(2, len(hiss)):
    whistle[t] = phi1 * whistle[t - 1] + phi2 * whistle[t - 2] + hiss[t]
save_wav("hiss.wav", hiss)
save_wav("whistle_440.wav", whistle)

p = pacf(whistle, nlags=10, method="ols")
print("Partial autocorrelations, lags 1-5:", np.round(p[1:6], 3))

# Now forget we know phi1 and phi2: estimate them from the sound, and recover the pitch
X = np.column_stack([whistle[1:-1], whistle[:-2]])
b1, b2 = np.linalg.lstsq(X, whistle[2:], rcond=None)[0]
pitch = np.arccos(b1 / (2 * np.sqrt(-b2))) * SR / (2 * np.pi)
print(f"Estimated phi1 = {b1:.4f}, phi2 = {b2:.4f}, so the pitch is {pitch:.1f} Hz")

fig, axes = plt.subplots(1, 2, figsize=(10, 3.2))
ms = 1000 * np.arange(441) / SR
axes[0].plot(ms, hiss[SR:SR + 441] / hiss.std(), linewidth=0.8, label="hiss")
axes[0].plot(ms, whistle[SR:SR + 441] / whistle.std(), linewidth=1.2, label="AR(2) whistle")
axes[0].set_title("20 ms of each (scaled to the same spread)", fontsize=9, loc="left")
axes[0].set_xlabel("Time (ms)")
axes[0].legend(loc="upper right", fontsize=8)
bars(axes[1], p[1:], len(whistle), "Whistle: partial autocorrelation")
axes[1].set_xlabel("Lag (samples)")
plt.tight_layout()
plt.show()
Listen: the white-noise hiss.
Listen: the same hiss through an AR(2) at 440 Hz. A breathy whistle on the A above middle C.
Left: 20 milliseconds of hiss, a jagged random line, overlaid with the AR(2) whistle, a smooth wave of nearly nine cycles whose height wanders. Right: the whistle's partial autocorrelation: a bar near +1 at lag 1, a bar near −1 at lag 2, and nothing after.
Left: 20 milliseconds of hiss, a jagged random line, overlaid with the AR(2) whistle, a smooth wave of nearly nine cycles whose height wanders. Right: the whistle's partial autocorrelation: a bar near +1 at lag 1, a bar near −1 at lag 2, and nothing after.

The partial autocorrelation shows the AR(2) fingerprint: two bars, about +0.99 and −0.99, then nothing. Fitting an AR(2) to the sound recovers the two numbers almost exactly, and from them the pitch: 440.0 Hz. Lesson 6.1 found a pitch from the autocorrelation peaks; this finds it from a two-number model.

This is more than a curiosity. An AR(2) is exactly the two-pole resonant filter in synthesisers: feed it noise and it whistles, feed it a buzz and it shapes the tone. And speech coding, the technology behind mobile phone calls since the 1990s, sends a fitted autoregression (of order 10 or more) for each slice of speech instead of the sound wave itself. It's called linear predictive coding, after the "predict today from the last few values" idea at its heart. The vocal tract is a set of resonances, and an AR model is a set of resonances.

Real data: loudness, and a zigzag in tempo

Now the yearly Spotify averages, 1950–2020. With only 71 years, the band is wide (±0.23), so only strong patterns will show.

Python
yearly = pd.read_csv("data_by_year.csv").set_index("year").loc[1950:2020]
loud = yearly["loudness"]
tempo_change = yearly["tempo"].diff().dropna()

fig, axes = plt.subplots(2, 2, figsize=(10, 5.4), sharex=True)
bars(axes[0, 0], acf(loud, nlags=12)[1:], len(loud), "Loudness: autocorrelation")
bars(axes[0, 1], pacf(loud, nlags=12, method="ols")[1:], len(loud), "Loudness: partial autocorrelation")
bars(axes[1, 0], acf(tempo_change, nlags=12)[1:], len(tempo_change), "Yearly change in tempo: autocorrelation")
bars(axes[1, 1], pacf(tempo_change, nlags=12, method="ols")[1:], len(tempo_change),
     "Yearly change in tempo: partial autocorrelation")
axes[1, 0].set_xlabel("Lag (years)")
axes[1, 1].set_xlabel("Lag (years)")
plt.tight_layout()
plt.show()

loud_change = loud.diff().dropna()
print("Loudness, partial autocorrelation lags 1-3:", np.round(pacf(loud, nlags=3, method="ols")[1:], 2))
print("Change in loudness, partial lags 1-3:      ", np.round(pacf(loud_change, nlags=3, method="ols")[1:], 2))
print("Change in tempo, autocorrelation lags 1-3: ", np.round(acf(tempo_change, nlags=3)[1:], 2))
print("Change in tempo, partial lags 1-3:         ", np.round(pacf(tempo_change, nlags=3, method="ols")[1:], 2))
counts = pd.read_csv("data.csv", usecols=["year"])["year"].value_counts().sort_index()
print(f"Tracks per year, 1950-2020: about {counts.loc[1950:2020].mean():,.0f}")
Four bar charts. Loudness autocorrelation: every bar from lag 1 to 12 is high, starting near 0.95 and declining slowly, all outside the band. Loudness partial autocorrelation: one bar near 1 at lag 1; the rest are small, with only lag 10 poking just outside the band. Yearly change in tempo, autocorrelation: one negative bar at lag 1, about −0.28, outside the band; the rest inside. Partial autocorrelation: one negative bar at lag 1, about −0.31, outside; the rest inside.
Four bar charts. Loudness autocorrelation: every bar from lag 1 to 12 is high, starting near 0.95 and declining slowly, all outside the band. Loudness partial autocorrelation: one bar near 1 at lag 1; the rest are small, with only lag 10 poking just outside the band. Yearly change in tempo, autocorrelation: one negative bar at lag 1, about −0.28, outside the band; the rest inside. Partial autocorrelation: one negative bar at lag 1, about −0.31, outside; the rest inside.

Loudness has the AR(1) fingerprint, with a coefficient of about 0.99: the autocorrelation fades very slowly, and the partial chart has one tall bar, almost touching 1. (The small bar at lag 10 that just crosses the band is the kind of chance crossing lesson 4.2 warned about: nothing happens to loudness every ten years.) An AR(1) with a coefficient of 1 is a random walk (lesson 3.2), so this is the same question lesson 4.1 struggled with: is loudness a random walk, or something very close to one? The charts can't settle it either. The yearly change in loudness has no bar outside the band, consistent with lesson 4.2's finding that the changes are white noise.

The yearly change in tempo has one bar outside the band in each chart, both negative and at lag 1. A rise one year tends to be followed by a fall the next: a zigzag. Where does that come from? Each year's average tempo is computed from a sample of about 2,000 tracks, so it carries some sampling noise: a year whose sample happens to include a few extra fast tracks reads too high. The next year's change then looks like a fall, simply because the noise doesn't repeat. Lesson 3.3 showed the same effect from the other side: differencing pure noise gives a lag-1 autocorrelation of −0.5. The underlying trend plus noise in the yearly averages produces exactly this MA(1)-like dip.

But look closely: with only 70 changes, both charts cut off after lag 1, so we can't tell whether this is an MA(1) or an AR(1). Telling them apart needs to see one chart fade gradually, and a fade of −0.3, then +0.09, then −0.03 is lost inside a band of ±0.23. That's an honest limit of the Box–Jenkins method: with short series, the fingerprints are smudged, and several models fit equally well.

What both charts miss: lag plots

Autocorrelation and partial autocorrelation measure straight-line relationships. A lag plot is the plain scatter plot behind them: each value against the value k steps earlier. Here's why you should always look at one.

The simulated series below follows a fixed rule, the logistic map, studied by the biologist Robert May (1976): next = 4 × now × (1 − now). There is no randomness at all; each value is completely determined by the previous one. We'll turn it into a melody by mapping each value to one of 15 notes: a five-note (pentatonic) scale starting on A, over three octaves:

Python
z = np.empty(500)
z[0] = 0.2
for t in range(1, len(z)):
    z[t] = 4 * z[t - 1] * (1 - z[t - 1])

print("Autocorrelation, lags 1-5:", np.round(acf(z, nlags=5)[1:], 3))
print(f"Ljung-Box p-value (10 lags): {acorr_ljungbox(z, lags=[10]).lb_pvalue.iloc[0]:.2f}")

scale = [0, 2, 4, 7, 9]                            # pentatonic steps, in semitones
notes = [220 * 2 ** ((12 * octave + step) / 12) for octave in range(3) for step in scale]


def melody(values, note_len=0.15):
    t = np.arange(int(note_len * SR)) / SR
    out = []
    for v in values:
        freq = notes[min(int(v * len(notes)), len(notes) - 1)]
        out.append(np.sin(2 * np.pi * freq * t) * np.exp(-6 * t))
    return np.concatenate(out)


save_wav("logistic_melody.wav", melody(z[:64]))
save_wav("shuffled_melody.wav", melody(rng.permutation(z[:64])))

fig, axes = plt.subplots(1, 3, figsize=(10, 3.2))
axes[0].plot(z[:60], marker=".", linewidth=0.8)
axes[0].set_title("Logistic map, first 60 steps", fontsize=9, loc="left")
bars(axes[1], acf(z, nlags=15)[1:], len(z), "Autocorrelation")
axes[2].scatter(z[:-1], z[1:], s=6)
axes[2].set_title("Lag plot: next value against this one", fontsize=9, loc="left")
axes[2].set_xlabel("Value now")
axes[2].set_ylabel("Next value")
plt.tight_layout()
plt.show()
Listen: 64 notes of the logistic-map melody.
Listen: the same 64 notes in a random order.
Left: the logistic map's first 60 values, jumping erratically between 0 and 1. Middle: its autocorrelation, all 15 bars small and inside the band. Right: its lag plot, every point lying exactly on an upside-down parabola, rising from 0 to a peak of 1 at the middle and falling back to 0.
Left: the logistic map's first 60 values, jumping erratically between 0 and 1. Middle: its autocorrelation, all 15 bars small and inside the band. Right: its lag plot, every point lying exactly on an upside-down parabola, rising from 0 to a peak of 1 at the middle and falling back to 0.

The autocorrelations are all close to zero, and the Ljung–Box test from lesson 4.2 is happy (p = 0.53): by every test so far, this is white noise. Yet the lag plot is a perfect curve. Know one value, and you know the next exactly. Autocorrelation misses it because the relationship is not a straight line: a value of 0.1 and a value of 0.9 both lead to 0.36, so on average, high and low values give no linear clue about what comes next.

Play the two melodies. The logistic melody isn't random: listen for runs where it sits on the top note and then crashes down, or creeps up from the bottom. The shuffled one has the same notes with no rule. But the difference is subtle, and many listeners can't hear it, which makes the point: zero autocorrelation means no straight-line memory, not no memory. Patterns like this, called nonlinear, are a whole field of time-series analysis.

Lag plots of real data

Pandas has a ready-made lag plot. Here it is for the Christmas pageviews (on a log scale) at lags of 1 and 365 days, and for loudness at a lag of 1 year:

Python
pv = pd.read_csv("christmas_pageviews.csv", parse_dates=["date"], index_col="date")["views"]
log_views = np.log(pv.asfreq("D"))

fig, axes = plt.subplots(1, 3, figsize=(10, 3.4))
pd.plotting.lag_plot(log_views, lag=1, ax=axes[0], s=3, alpha=0.4)
axes[0].set_title("Christmas views: today vs yesterday", fontsize=9, loc="left")
pd.plotting.lag_plot(log_views, lag=365, ax=axes[1], s=3, alpha=0.4)
axes[1].set_title("Today vs a year ago", fontsize=9, loc="left")
pd.plotting.lag_plot(loud, lag=1, ax=axes[2], s=12)
axes[2].set_title("Loudness: this year vs last (dB)", fontsize=9, loc="left")
plt.tight_layout()
plt.show()

print(f"Lag-1 correlation of log views: {log_views.autocorr(1):.2f}; lag-365: {log_views.autocorr(365):.2f}")
Three lag plots. Christmas views (log) today against yesterday: points packed tightly along the diagonal, densest at the bottom left (ordinary days) and running up to the December peaks at the top right. Today against a year ago: a broader cloud along the same diagonal, with more scattered points, but the December days still line up at the top right. Loudness this year against last year: points close to the diagonal, running from about −16 dB at the bottom left to about −7 dB at the top right.
Three lag plots. Christmas views (log) today against yesterday: points packed tightly along the diagonal, densest at the bottom left (ordinary days) and running up to the December peaks at the top right. Today against a year ago: a broader cloud along the same diagonal, with more scattered points, but the December days still line up at the top right. Loudness this year against last year: points close to the diagonal, running from about −16 dB at the bottom left to about −7 dB at the top right.

These are the pictures behind three numbers you've seen before. Today against yesterday is a tight diagonal (correlation 0.98): views change slowly from day to day. Today against a year ago is looser, but it holds together, and the December days still line up at the top right: the yearly beat from lesson 6.1.

The lag-365 number here is 0.95, higher than the 0.85 that acf gave in lesson 6.1. That's not a mistake. Pandas' .autocorr is the plain correlation of the pairs in the plot. acf measures every lag against the mean and spread of the whole series, which pulls long-lag values towards zero but keeps the whole chart consistent and stable. The two agree at short lags and drift apart at long ones, so when you compare numbers, compare like with like. Loudness hugs the diagonal: each year is very like the last, the AR(1)-close-to-1 fingerprint we saw above. None of these plots bends like the logistic map, so for these series, straight-line measures like autocorrelation are telling the whole story.

Key ideas

  • Autocorrelation counts direct and inherited memory together. In an AR(1), lag 2 is correlated only because both are linked to lag 1.
  • Partial autocorrelation at lag k is the extra information lag k adds once lags 1 to k − 1 are known. It's the last coefficient in a regression on the last k values.
  • Box–Jenkins fingerprints: a cut-off in the partial chart after lag p suggests AR(p); a cut-off in the ordinary chart after lag q suggests MA(q).
  • An AR(2) can make cycles: in audio, it's a resonant filter, and fitting one to a sound recovers its pitch.
  • Loudness looks like an AR(1) with a coefficient of about 0.99. Yearly tempo changes zigzag, the mark of sampling noise in yearly averages. With 70 points, AR and MA can't be told apart.
  • Lag plots show relationships that aren't straight lines. The logistic map passes every white-noise test yet is perfectly predictable.

Try it yourself

  1. Simulate an MA(2), e[2:] + 0.8 * e[1:-1] + 0.5 * e[:-2], and draw both charts. Where does each one cut off?
  2. In the whistle, change 440 to 262 (middle C) and ring to 0.95. What happens to the sound, and to the estimated pitch?
  3. Draw the partial autocorrelation of the yearly change in danceability. Is there a zigzag like tempo's?
  4. Make a lag plot of the logistic map at lag 2. What shape do you see, and why?

Next lesson: How forecastable is a hit?

The course

Music as Data: Time Series with Python

Course home
  1. 1Music as a time series

  2. 2Seeing patterns

  3. 3Decomposition and stationarity

  4. 4Testing a time series

  5. 5Missing values

  6. 6Autocorrelation and forecasting

  7. 7Smoothing and Granger causality

  8. 8From time series to AI music