Ainsteinx Logo
Ainsteinx
👤
ยินดีต้อนรับสู่ Ainsteinx
เข้าสู่ระบบ

เปลี่ยนภาษา

สกุลเงิน

หน้าแรก
บล็อก
บริการ
บทที่ 11 · การนำไปใช้

แต่งเพลงด้วย 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 เรียนคีย์และสเกลได้เอง เพียงจากการทายโน้ตถัดไป
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()}")

ผลลัพธ์

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
  • #ບອກຕໍ່ຄວາມຮູ້