แต่งเพลงด้วย AI
โน้ตเพลงก็คือ token: ทายโน้ตถัดไปเหมือนทายคำถัดไป
เพลงมีทั้ง pitch และ duration จึงใช้ Transformer ที่มี input/output 2 สาย เพลงหลายเสียง (polyphonic) ต้องเลือกวิธี tokenize: grid (แบ่งเวลาเป็นช่อง) หรือ event (ลำดับคำสั่ง) ส่วน MuseGAN ใช้ convolution สร้างเพลงหลาย track เหมือนสร้างภาพ
โค้ดตัวอย่างใช้ autoregressive model ที่ง่ายที่สุด (bigram) กับ token แบบ โน้ต:ความยาว และแต่งเพลงสั้น 3 ท่อน
| วิธี | แนวคิด |
|---|---|
| Transformer (note + duration) | 2 embedding รวมกัน ทายทั้งโน้ตและความยาวถัดไป |
| Grid tokenization | แบ่งเวลาเป็นช่องเท่ากัน แล้วอ่านทุกเสียงเป็นสายเดียว |
| Event tokenization | เขียนเป็นคำสั่ง: กดโน้ต รอ ปล่อยโน้ต |
| MuseGAN | มองเพลงเป็นภาพ (piano roll) แล้วใช้ GAN |
สิ่งที่ควรจำ
- ผลของ AI แต่งเพลงขึ้นกับวิธี tokenize อย่างมาก
- Model เรียนคีย์และสเกลได้เอง เพียงจากการทายโน้ตถัดไป
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
- #ບອກຕໍ່ຄວາມຮູ້