AI 作曲
音符也是 token:像预测下一个词那样预测下一个音符。
音乐既有音高也有时值,所以 Transformer 使用两路输入/输出。复调音乐需要选择分词方式:网格式(按固定时间格划分)或事件式(指令序列)。MuseGAN 则用卷积像生成图像一样生成多轨乐谱。
示例用最简单的自回归模型(二元模型)处理“音符:时值”token,创作三段短旋律。
| 方法 | 思路 |
|---|---|
| Transformer (note + duration) | 两个嵌入相加,同时预测下一个音符和时值 |
| Grid tokenization | 按等长时间格划分,把所有声部读成一条序列 |
| Event tokenization | 写成指令:按下音符、等待、松开音符 |
| MuseGAN | 把乐谱看作图像(钢琴卷帘)并使用 GAN |
要点
- AI 作曲的效果在很大程度上取决于分词方式
- 模型仅靠预测下一个音符,就能自行学会调性和音阶
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()}")
输出结果
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
- #ບອກຕໍ່ຄວາມຮູ້