Lesson 8.1Module 8: From time series to AI music50 minIntermediate

From forecasting to generating: how AI music models predict what comes next

A forecasting model becomes a music generator the moment you sample from it instead of taking its average. Generate futures for a real series, build a melody generator from four public-domain tunes, and test it the way this course tests forecasts, including the point where it stops creating and starts copying.

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

This course has spent seven modules forecasting: given the past, what comes next? AI music generators answer exactly the same question, over and over. Feed a model the notes (or sound) so far, ask it for the next one, add the answer to the end, and repeat. The only real difference between forecasting and generating is what you do with the forecast. In this last lesson, you'll turn a forecast into a generator, build a small melody generator, judge it with the backtesting ideas from lesson 6.3, and find the point where it stops composing and starts copying, the question at the centre of today's arguments about AI music.

Set up

You need data_by_year.csv from the Spotify dataset (lesson 2.1). The melodies are typed in below.

Python
import wave
from collections import Counter, defaultdict

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

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


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

The average future versus a possible future

Lesson 6.2 found that yearly loudness behaves like an AR(1): each year is close to the previous year, plus a random shock. Let's fit that model to 1950–2020 and ask it about 2021–2040 in two different ways.

  • Forecasting: at each step, use the model's expected next value: no shock, because the average shock is zero.
  • Generating: at each step, draw a random shock of the size the model has seen, and add it. Each run gives a different, possible future.
Python
loud = pd.read_csv("data_by_year.csv").set_index("year")["loudness"].loc[1950:2020]

# Fit loudness_t = c + phi * loudness_(t-1) + shock, by least squares
X = np.column_stack([np.ones(len(loud) - 1), loud.to_numpy()[:-1]])
(c, phi), *_ = np.linalg.lstsq(X, loud.to_numpy()[1:], rcond=None)
shock_sd = np.std(loud.to_numpy()[1:] - X @ np.array([c, phi]), ddof=2)
print(f"loudness_t = {c:.3f} + {phi:.3f} x loudness_(t-1) + shock (sd {shock_sd:.2f} dB)")

years = np.arange(2021, 2041)


def run_forward(start, sample):
    path, level = [], start
    for _ in years:
        level = c + phi * level + (rng.normal(0, shock_sd) if sample else 0)
        path.append(level)
    return np.array(path)


forecast = run_forward(loud.iloc[-1], sample=False)
futures = [run_forward(loud.iloc[-1], sample=True) for _ in range(5)]
print(f"Forecast for 2040: {forecast[-1]:.1f} dB.  Five generated 2040s: "
      + ", ".join(f"{f[-1]:.1f}" for f in futures))

fig, ax = plt.subplots(figsize=(10, 3.8))
ax.plot(loud, color="grey", label="actual, 1950-2020")
for i, f in enumerate(futures):
    ax.plot(years, f, linewidth=1, alpha=0.8, label="generated futures" if i == 0 else None)
ax.plot(years, forecast, color="C1", linewidth=2.5, linestyle="--", label="forecast (the average future)")
ax.set_ylabel("Average loudness (dB)")
ax.set_title("Forecasting versus generating: loudness after 2020", loc="left")
ax.legend(loc="upper left")
plt.show()
Average loudness from 1950 to 2020 in grey, rising from about −16 to about −7 dB with year-to-year wobbles. After 2020, a thick dashed forecast line rises smoothly and gently, from about −6.6 to −5.7 dB in 2040. Five thinner generated paths start at the same point and wander up and down around it, each with wobbles like the real history, spreading apart over time: by 2040 one is near 0 dB and another near −8 dB.
Average loudness from 1950 to 2020 in grey, rising from about −16 to about −7 dB with year-to-year wobbles. After 2020, a thick dashed forecast line rises smoothly and gently, from about −6.6 to −5.7 dB in 2040. Five thinner generated paths start at the same point and wander up and down around it, each with wobbles like the real history, spreading apart over time: by 2040 one is near 0 dB and another near −8 dB.

The fitted model is: this year's loudness = −0.039 + 0.987 × last year's + a shock with a spread of 0.52 dB. The forecast is a single smooth line, creeping up from 2020's level to −5.7 dB by 2040. No real series looks like that: it has no wobbles at all. It's the average of all the futures the model thinks possible, and an average of wobbly paths is smooth.

The generated futures look like real history: each has year-to-year wobbles of the right size. But they disagree wildly about 2040, from −8.2 dB to −0.5 dB, which would be louder than any year on record. They aren't forecasts; each is one plausible story, and the spread between them is the forecast's uncertainty, made visible. (They also inherit the model's flaws. With a coefficient so close to 1, the model's idea of the long-run level, −0.039 / (1 − 0.987), about −3 dB, is very poorly pinned down, the same difficulty lesson 4.1 met. The model doesn't know the loudness war ended.)

That's the whole difference between forecasting and generating. A forecaster reports the average; a generator draws a sample. An AI music model that always chose the single most likely next sound would be as lifeless as that dashed line.

A melody generator

Now music. We'll write melodies as tokens: one number per note, its MIDI pitch (lesson 1.3: middle C is 60, each step up a semitone adds 1). For simplicity, every note has the same length. Here are four public-domain melodies in C major:

Python
G3 = 55                                            # the G below middle C
C, D, E, F, G, A = 60, 62, 64, 65, 67, 69

tunes = {
    "Twinkle, Twinkle, Little Star": [C, C, G, G, A, A, G, F, F, E, E, D, D, C,
                                      G, G, F, F, E, E, D, G, G, F, F, E, E, D,
                                      C, C, G, G, A, A, G, F, F, E, E, D, D, C],
    "Ode to Joy (Beethoven)": [E, E, F, G, G, F, E, D, C, C, D, E, E, D, D,
                               E, E, F, G, G, F, E, D, C, C, D, E, D, C, C,
                               D, D, E, C, D, E, F, E, C, D, E, F, E, D, C, D, G3,
                               E, E, F, G, G, F, E, D, C, C, D, E, D, C, C],
    "Frère Jacques": [C, D, E, C, C, D, E, C, E, F, G, E, F, G,
                      G, A, G, F, E, C, G, A, G, F, E, C, C, G3, C, C, G3, C],
    "Mary Had a Little Lamb": [E, D, C, D, E, E, E, D, D, D, E, G, G,
                               E, D, C, D, E, E, E, E, D, D, E, D, C],
}
print({name: len(notes) for name, notes in tunes.items()})


def play(notes, note_len=0.28):
    t = np.arange(int(note_len * SR)) / SR
    parts = []
    for m in notes:
        f = 440 * 2 ** ((m - 69) / 12)            # MIDI number to frequency (lesson 1.3)
        tone = sum(np.sin(2 * np.pi * h * f * t) / h ** 2 for h in range(1, 5))
        parts.append(tone * np.exp(-5 * t))
    return np.concatenate(parts)


save_wav("ode_to_joy.wav", play(tunes["Ode to Joy (Beethoven)"]))
Listen: the training melody Ode to Joy, as the generator will hear it: equal-length notes, no rhythm.

The simplest model of "what note comes next" is a Markov chain, named after the Russian mathematician Andrey Markov, who in 1913 counted how vowels and consonants follow one another in Pushkin's verse novel Eugene Onegin. Count, in the training tunes, how often each note follows each context (the last k notes). Those counts, turned into shares, are the forecast: a probability for every possible next note. The number k is the model's order, just like the order of an AR model in lesson 6.2.

Python
START = "start"


def train(tune_list, k):
    counts = defaultdict(Counter)
    for notes in tune_list:
        padded = [START] * k + notes
        for i in range(k, len(padded)):
            counts[tuple(padded[i - k:i])][padded[i]] += 1
    return counts


vocab = sorted({m for notes in tunes.values() for m in notes})
model1 = train(tunes.values(), 1)
grid = np.array([[model1[(a,)][b] for b in vocab] for a in vocab], dtype=float)
grid = grid / grid.sum(axis=1, keepdims=True)

names = {55: "G3", 60: "C", 62: "D", 64: "E", 65: "F", 67: "G", 69: "A"}
fig, ax = plt.subplots(figsize=(6, 5))
im = ax.imshow(grid, cmap="magma", vmin=0, vmax=1)
ax.set_xticks(range(len(vocab)), [names.get(m, m) for m in vocab])
ax.set_yticks(range(len(vocab)), [names.get(m, m) for m in vocab])
ax.set_xlabel("Next note")
ax.set_ylabel("This note")
ax.set_title("Order-1 forecast: chance of each next note", loc="left", fontsize=10)
ax.grid(False)
plt.colorbar(im, ax=ax, fraction=0.046)
plt.show()
print("After E, the next note is:", {names[m]: f"{n / sum(model1[(E,)].values()):.0%}" for m, n in model1[(E,)].most_common()})
A grid of probabilities, with the current note down the side and the next note along the bottom, for the seven notes G3, C, D, E, F, G and A. Most bright squares sit on or next to the diagonal: notes are mostly followed by themselves or by a neighbouring note one step up or down. The brightest squares: low G3 is followed by C about two times in three, A by G about two times in three, and F by E about half the time.
A grid of probabilities, with the current note down the side and the next note along the bottom, for the seven notes G3, C, D, E, F, G and A. Most bright squares sit on or next to the diagonal: notes are mostly followed by themselves or by a neighbouring note one step up or down. The brightest squares: low G3 is followed by C about two times in three, A by G about two times in three, and F by E about half the time.

Each row is a forecast. After E, the training tunes went to D 37% of the time, stayed on E 30%, went up to F 16%, down to C 14% and jumped to G 2%. The brightest squares hug the diagonal: in these tunes, melodies mostly move by step or repeat a note, which is true of most melodies everywhere. This grid is a complete order-1 model of "how melodies move", learned from 162 notes.

Generating: sample, append, repeat

To generate, start with the context of START tokens, sample the next note from the forecast probabilities, append it, and repeat. This is how every autoregressive generator works, from this one to the largest AI music models.

There's one more control, called temperature. Raising each probability to the power 1/T and rescaling makes the model bolder (T above 1: unlikely notes get more chances) or more cautious (T below 1: it sticks to the most likely notes). At T near 0, it always picks the single most likely note: that's the forecast, not a sample.

Python
def next_probs(model, context, temperature=1.0):
    counts = model.get(tuple(context))
    if not counts:                                 # a context never seen in training
        return None
    notes = list(counts)
    p = np.array([counts[m] for m in notes], dtype=float) ** (1 / temperature)
    return notes, p / p.sum()


def generate(model, k, length=32, temperature=1.0):
    out = [START] * k
    while len(out) - k < length:
        options = next_probs(model, out[len(out) - k:], temperature)   # the last k notes (works for k = 0 too)
        if options is None:                        # dead end: start a new phrase
            out += [START] * k
            continue
        notes, p = options
        out.append(notes[rng.choice(len(notes), p=p)])
    return [m for m in out if m != START][:length]


models = {k: train(tunes.values(), k) for k in (1, 2, 4)}
melodies = {k: generate(models[k], k) for k in (1, 2, 4)}
for k, notes in melodies.items():
    print(f"Order {k}:", " ".join(names[m] for m in notes))
    save_wav(f"generated_order{k}.wav", play(notes))
Listen: a melody generated by the order-1 model.
Listen: a melody generated by the order-2 model.
Listen: a melody generated by the order-4 model.

Here are the melodies this run generated:

  • Order 1: E D C D C D D C C C D C D E C C C C C D E D C G3 C D E E D E C C. Every step is plausible (it only ever moves the way the tunes move), but it wanders: it has no memory beyond one note, so it has no phrases. It also hangs around C, D and E, the busiest notes in the training tunes.
  • Order 2: E D C C D G3 E E D D C D E C D E E E D D E C C D E D D D C C D E. Short fragments of real phrases appear ("C D E", "E E D D") and are stitched together.
  • Order 4: C D E C C D E C C D E C E F G E F G G F E D C C D D E C D E F E. That's the opening of Frère Jacques, almost exactly, followed by pieces of Ode to Joy. With four notes of context, most contexts occurred only once in training, so there's only one possible next note: the model plays back what it memorised.

Your melodies will differ (they're random), but the pattern holds: more context gives more musical-sounding output, and then more copying.

Judging a generator like a forecaster

How do you know whether a generator is any good? The standard score in AI is the one a forecaster would use: how well does the model forecast the next token in music it hasn't seen? For probability forecasts, the score is the log loss: the average of −log₂ of the probability the model gave to the note that actually came next. It's measured in bits: a model that gave the right note a probability of ½ every time would score 1 bit, a model that was always certain and right would score 0, and lower is better. (Language models report the same thing, often converted into "perplexity", 2 to the power of the log loss.)

To test on unseen music, we use leave-one-out cross-validation, the backtest idea from lesson 6.3 for data without a time order: train on three tunes, score the fourth, and repeat for each tune. A model that has never seen a context gives up and spreads its bets evenly over all 7 notes, which scores log₂ 7 = 2.81 bits. For contexts it has seen, we blend its forecast with that even spread, keeping 10% for surprises, so it never gives a note zero chance.

We'll also measure copying: what share of the 8-note stretches in long generated melodies appear, note for note, in the training tunes?

Python
def log_loss(model, k, notes, keep=0.9):
    padded = [START] * k + notes
    total = 0.0
    for i in range(k, len(padded)):
        counts = model.get(tuple(padded[i - k:i]), Counter())
        seen = sum(counts.values())
        p_model = counts[padded[i]] / seen if seen else 0.0
        p = keep * p_model + (1 - keep) / len(vocab) if seen else 1 / len(vocab)
        total += -np.log2(p)
    return total / len(notes)


def copied_share(k, n_melodies=50, stretch=8):
    training = set()
    for notes in tunes.values():
        training |= {tuple(notes[i:i + stretch]) for i in range(len(notes) - stretch + 1)}
    hits = total = 0
    for _ in range(n_melodies):
        g = generate(models_all[k], k, length=64)
        windows = [tuple(g[i:i + stretch]) for i in range(len(g) - stretch + 1)]
        hits += sum(w in training for w in windows)
        total += len(windows)
    return hits / total


orders = [0, 1, 2, 3, 4, 6]
models_all = {k: train(tunes.values(), k) for k in orders}
rows = []
for k in orders:
    train_loss = np.mean([log_loss(models_all[k], k, notes) for notes in tunes.values()])
    test_loss = np.mean([log_loss(train([v for n, v in tunes.items() if n != held], k), k, tunes[held])
                         for held in tunes])
    rows.append((k, train_loss, test_loss, copied_share(k)))
scores = pd.DataFrame(rows, columns=["order", "loss on training tunes", "loss on unseen tune", "copied"]).set_index("order")
print(scores.round(2).to_string())

fig, axes = plt.subplots(1, 2, figsize=(10, 3.4))
axes[0].plot(scores.index, scores["loss on training tunes"], marker="o", label="training tunes")
axes[0].plot(scores.index, scores["loss on unseen tune"], marker="o", label="unseen tune (left out)")
axes[0].set_xlabel("Order (notes of context)")
axes[0].set_ylabel("Log loss (bits per note)")
axes[0].set_title("Forecasting the next note", fontsize=10, loc="left")
axes[0].legend(fontsize=8)
axes[1].plot(scores.index, 100 * scores["copied"], marker="o", color="C1")
axes[1].set_xlabel("Order (notes of context)")
axes[1].set_ylabel("% of 8-note stretches")
axes[1].set_title("Generated stretches copied from training", fontsize=10, loc="left")
axes[1].set_ylim(0, 105)
plt.tight_layout()
plt.show()
Two line charts against model order 0 to 6. Left: log loss on the training tunes falls steadily as the order rises, towards zero; log loss on the unseen tune is lowest at order 1, climbs to a peak at order 3, then drifts back down at orders 4 and 6. Right: the share of generated 8-note stretches copied from the training tunes climbs from near zero at order 0 to nearly 100% at the highest orders.
Two line charts against model order 0 to 6. Left: log loss on the training tunes falls steadily as the order rises, towards zero; log loss on the unseen tune is lowest at order 1, climbs to a peak at order 3, then drifts back down at orders 4 and 6. Right: the share of generated 8-note stretches copied from the training tunes climbs from near zero at order 0 to nearly 100% at the highest orders.

Read the two charts together:

  • On the training tunes, the log loss falls steadily with order, from 2.51 bits at order 0 (just the overall note frequencies) to 0.27 bits at order 6. With enough context, the model almost knows each next note, because it has memorised the tunes.
  • On the unseen tune, the best order is 1 (2.37 bits). Order 2 is already worse (3.22), and order 3 is the worst of all (3.70 bits), worse even than the 2.81 bits of the even-spread guess. That's what over-confidence costs: when an order-3 model has seen a context, it bets heavily on the note that followed it in another tune, and when that bet is wrong, the log loss punishes it hard. At orders 4 and 6 the loss comes back down (3.33 and 2.87), not because the models are better but because almost every context in the new tune is one they've never seen, so they fall back on the even spread.
  • Copying climbs with order: about 1% of 8-note stretches are copied at order 1, 7% at order 2, 24% at order 3, 60% at order 4 and 91% at order 6.

This is overfitting, the same trap as fitting too many lags to a short time series, and the copying chart shows it in a form you can hear. The model that scores best on the music it learned from is the worst at forecasting music it hasn't heard, and it composes by playing back its training data. With 162 notes of training data, the best this model can do is a single note of context.

From here to real AI music

Today's AI music systems are this lesson's generator, scaled up enormously:

  • Bigger contexts. Instead of the last 1–6 notes, a neural network called a transformer (Vaswani and colleagues, 2017) looks back over thousands of tokens, and learns which earlier ones matter: a melody's opening, the chord two bars ago.
  • Smarter counting. A Markov chain can only forecast a context it has seen exactly. A neural network learns similarities between contexts, so it can forecast sensibly in situations it has never met. That's what keeps a large model off the left-hand chart's rising curve.
  • Audio tokens. Instead of MIDI pitches, many models forecast compressed pieces of sound. WaveNet (van den Oord and colleagues, 2016) forecast raw audio one sample at a time, 16,000 samples a second, using exactly the "sample, append, repeat" loop. Later systems such as Google's MusicLM (2023) and Meta's MusicGen (Copet and colleagues, 2023) first compress audio into tokens, about 50 steps a second for MusicGen, then forecast those. Commercial services such as Suno and Udio haven't published their methods in detail, so how they work is not publicly known.
  • Conditioning. A text prompt ("upbeat Christmas pop") is extra information the model uses when forecasting, like the outside information in lessons 6.3 and 7.2.
  • The same tensions. Real models also face the trade-off on the right-hand chart. A model that predicts its training music too well can reproduce it, and in 2024 the major record labels sued Suno and Udio, alleging that their models were trained on copyrighted recordings. How much a model memorises, and how to measure it, is an open research question, and the copying test above is a toy version of the methods researchers use.

Everything in this course carries over. A generated piece is a time series. Its loudness has a trend and an envelope; its rhythm shows up in the autocorrelation; its "surprise" is a forecast error. If you can analyse music as data, you can understand, and critically judge, the machines that make it.

Key ideas

  • A forecast is the average future; a generated path is one possible future, made by sampling the shocks. Generators sample; forecasters average.
  • Autoregressive generation: forecast the next token, sample it, append it, repeat. Markov chains, WaveNet and modern AI music models all work this way.
  • A Markov chain of order k forecasts the next note from counts of what followed the last k notes. Temperature controls how bold its samples are.
  • Judge a generator like a forecaster: log loss on unseen music, using held-out data (the backtest idea).
  • More context fits the training music better, but past a point it forecasts unseen music worse and copies more. Memorisation is overfitting you can hear.

Try it yourself

  1. Generate with the order-2 model at temperatures 0.3, 1 and 3. Describe what you hear. At what temperature does it start copying whole phrases?
  2. Add a fifth public-domain tune in C major (for example "London Bridge Is Falling Down") and rerun the scoring. Which orders improve most on the unseen tune, and why?
  3. Change the 10% kept for surprises in log_loss to 1% and to 50%. How does the best order change?
  4. Use the loudness model to generate 1,000 futures to 2040. What share of them end up louder than −5 dB? Compare that with the single forecast.

You've finished the course. Thank you for working through Music as Data. Go back to the course page to revisit any lesson, and look out for new lessons, including one on structural breaks: the sudden changes in loudness and release days that kept appearing in this course.

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