Ainsteinx Logo
Ainsteinx
👤
Welcome to Ainsteinx
Login

Change Language

Currency

Home
Blog
Services
Lesson 11 · Applications

Music generation

Notes are tokens too: predict the next note like the next word.

Music has both pitch and duration, so the Transformer gets two input/output streams. Polyphonic music needs a tokenisation choice: grid (fixed time slots) or event-based (a sequence of instructions). MuseGAN instead uses convolutions to generate multi-track scores like images.

The example uses the simplest autoregressive model — a bigram — over note:duration tokens and composes three short melodies.

ApproachIdea
Transformer (note + duration)Two embeddings combined; predicts next note and duration
Grid tokenizationEqual time steps, all voices read as one stream
Event tokenizationInstructions: note on, wait, note off
MuseGANTreats the score as an image (piano roll) and uses a GAN

Key takeaways

  • Music models live or die by their tokenisation
  • Models learn keys and scales on their own just by predicting the next note
generative-ai-ep11-music.py
import numpy as np

rng = np.random.default_rng(1)
# A tiny corpus of melodies as (note, duration) tokens
songs = [
    "C4:1 E4:1 G4:1 E4:1 C4:2", "C4:1 D4:1 E4:1 G4:1 E4:2",
    "E4:1 G4:1 A4:1 G4:1 E4:2", "G4:1 E4:1 D4:1 C4:1 C4:2",
]
tokens = [s.split() + ["END"] for s in songs]
vocab = sorted({t for song in tokens for t in song} | {"START"})
ix = {t: i for i, t in enumerate(vocab)}

# Bigram model p(next | current): the simplest autoregressive music model
counts = np.zeros((len(vocab), len(vocab)))
for song in tokens:
    for a, b in zip(["START"] + song, song):
        counts[ix[a], ix[b]] += 1
probs = counts / np.maximum(counts.sum(1, keepdims=True), 1)

def compose(max_len=10):
    cur, out = "START", []
    for _ in range(max_len):
        cur = vocab[rng.choice(len(vocab), p=probs[ix[cur]])]
        if cur == "END": break
        out.append(cur)
    return " ".join(out)

for i in range(3):
    print(f"melody {i + 1}: {compose()}")

Output

melody 1: E4:1 G4:1 A4:1 G4:1 E4:1 G4:1 E4:2
melody 2: E4:1 C4:2
melody 3: E4:1 D4:1 E4:1 D4:1 C4:1 C4:2
  • #GenerativeAI
  • #DeepLearning
  • #PythonສຳລັບຄົນLaos
  • #AI
  • #ບອກຕໍ່ຄວາມຮູ້