Saturday, November 21, 2026

Neural Sequence Models (NLP-05)

Artificial Intelligence: A Modern Approach (4th Edition) စာအုပ် Chapter 24 (Deep Learning for Natural Language Processing — Section 24.2: Recurrent Neural Networks & LSTMs) ပါ Neural Sequence Models သီအိုရီများကို Books စာအုပ်ဒေတာစု (Books / language / author / title.txt) ပေါ်တွင် Character-Level LSTM ဖြင့် လက်တွေ့တည်ဆောက် စမ်းသပ်ထားပါသည်။

၁။ AIMA Chapter 24.2 ပါ သီအိုရီ အခြေခံ ၄ ရပ်

  1. N-Gram ၏ အကန့်အသတ်နှင့် Recurrent Neural Networks (RNNs) ယခင် N-gram မော်ဒယ်များသည် Markov Assumption အရ ရှေ့ကပ်လျက် စကားလုံး  လုံးကိုသာ ကြည့်ရှုနိုင်သဖြင့် ဝါကျရှည်များအတွင်းရှိ အဖွင့်အပိတ် မျက်တောင်အမှတ်အသား ("...") များ၊ ကွင်းစကွင်းပိတ်များနှင့် ဝါကျအစ/အဆုံး ဆက်စပ်မှု (Long-Range Dependencies) များကို မမှတ်မိနိုင်ပါ။ RNN သည် အချိန်အမှတ်  တိုင်းတွင် လက်ရှိသွင်းအားစု  နှင့် ယခင်အဆင့်မှ မှတ်ဉာဏ်ဗက်တာ  တို့ကို ပေါင်းစပ်၍ Hidden State () အဖြစ် အဆက်မပြတ် သယ်ဆောင်သွားပါသည်။

  1. Backpropagation Through Time (BPTT) နှင့် Vanishing / Exploding Gradients RNN ကို အချိန်အဆင့်  ဆင့်အထိ ဖြန့်ချ၍ လေ့ကျင့်သောအခါ (BPTT), အမှားပြင်ဆင်မှု Gradient သည် အလေးချိန်မက်ထရစ်  ဖြင့်  ကြိမ်တိုင်တိုင် ဆက်တိုက်မြှောက်ရပါသည်။
    • Vanishing Gradient () Gradient တန်ဖိုးများ သုညနီးပါး သေးငယ်ပျောက်ကွယ်သွားသဖြင့် မော်ဒယ်သည် အစောပိုင်းစာသားများကို မေ့လျော့သွားပါသည်။
    • Exploding Gradient (): Gradient တန်ဖိုးများ အဆမတန် ကြီးထွားပေါက်ကွဲသွားသဖြင့် Gradient Clipping () ဖြင့် ဖြတ်တောက်ထိန်းသိမ်းရပါသည်။
  2. Long Short-Term Memory (LSTM — Hochreiter & Schmidhuber, 1997) Vanishing Gradient ပြဿနာကို ဖြေရှင်းရန် LSTM သည် သီးခြား Cell State () (သတင်းအချက်အလက် အဝေးပြေးလမ်းမကြီး) ကို ထားရှိပြီး Sigmoid Gate () ၃ ခုဖြင့် မှတ်ဉာဏ်အဝင်အထွက်ကို ထိန်းချုပ်ပါသည်—
    • Forget Gate () မလိုအပ်တော့သော မှတ်ဉာဏ်ဟောင်းများကို ဖျက်ပစ်ခြင်း (ဥပမာ — ဝါကျတစ်ကြောင်း ပြီးဆုံးသွားချိန်)။
    • Input Gate () နှင့် Candidate Memory () လက်ရှိအက္ခရာအသစ်မှ အရေးကြီးသော အချက်အလက်များကို မှတ်ဉာဏ်ထဲသို့ ပေါင်းထည့်ခြင်း။
    • Additive Cell Update  (မြှောက်လဒ်အစား ပေါင်းလဒ်ကို သုံးထားသဖြင့် Gradient မပျောက်ကွယ်ဘဲ အဝေးကြီးသို့ စီးဆင်းနိုင်သည်)။
    • Output Gate () နှင့် Hidden State ။
  3. Temperature-Controlled Softmax Sampling () စာသားအသစ်များ ထုတ်လုပ်ရာတွင် Neural Network မှ ထွက်လာသော Logits  ကို Temperature () ဖြင့် စား၍ ဖြစ်နိုင်ခြေဖြန့်ဝေမှုကို ချိန်ညှိပါသည်။

    •  နိမ့်လျှင် (0.4) စာလုံးပေါင်းနှင့် သဒ္ဒါ အလွန်သေချာသော်လည်း စကားစုများ ထပ်တလဲလဲ ဖြစ်တတ်သည်။
    •  အလယ်အလတ် (0.75) စာလုံးပေါင်း မှန်ကန်မှုနှင့် ဖန်တီးနိုင်စွမ်း မျှတပြီး စာရေးဆရာ၏ လေယူလေသိမ်း အပီပြင်ဆုံး ထွက်ပေါ်သည်။
    •  မြင့်လျှင် (1.15) စကားလုံးအသစ်အဆန်းများ ပိုမိုထွက်ပေါ်သော်လည်း စာလုံးပေါင်းမှားယွင်းနိုင်ခြေ မြင့်တက်လာသည်။


၂။ AIMA သီအိုရီ များပါဝင်သော PyTorch Code

အောက်ပါ ပရိုဂရမ်သည် စာလုံးအကြီး/အသေးနှင့် ပုဒ်ဖြတ်ပုဒ်ရပ်များကို လုံးဝမဖျက်ဘဲ မူရင်းစာသားအတိုင်း သင်ကြားပေးသဖြင့် Neural Network ကိုယ်တိုင် စာလုံးပေါင်းသတ်ပုံ၊ စာကြောင်းအစ စာလုံးအကြီးတင်ပုံ၊ ကော်မာနှင့် မျက်တောင်အဖွင့်အပိတ် အသုံးပြုပုံ တို့ကို အက္ခရာတစ်လုံးချင်းစီမှ အလိုအလျောက် သင်ယူတတ်မြောက်သွားမည် ဖြစ်ပါသည်။
Python
# -*- coding: utf-8 -*-
"""
AIMA (4th Ed.) Chapter 24, Section 24.2:
Neural Sequence Models — Character-Level Vanilla RNN vs. LSTM
BPTT, Gradient Clipping, Temperature Sampling & Internal Memory Visualization
"""

import os
import math
import time
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA

try:
    import torch
    import torch.nn as nn
    from torch.utils.data import Dataset, DataLoader
except ImportError as exc:
    raise ImportError(
        "ဤပရိုဂရမ်အတွက် PyTorch လိုအပ်ပါသည်။ Anaconda Prompt / Terminal တွင် "
        "'pip install torch' ဖြင့် ထည့်သွင်းပြီး ပြန်လည် Run ပေးပါ။"
    ) from exc

plt.style.use('ggplot')
np.random.seed(42)
torch.manual_seed(42)

DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
BOOK_DIR = r"C:\Users\kks\OneDrive\Desktop\MyPyTest\Module4\Datasets\Books"


# ==============================================================================
# အပိုင်း (၁) - မူရင်းစာသား (Raw Characters & Punctuation) ဖတ်ယူခြင်း
# AIMA (4th Ed.) Ch. 24, Sec. 24.2 (Character-Level Sequence Modeling)
# သီအိုရီ -
#   Word-level မော်ဒယ်များနှင့် မတူဘဲ Character-Level Neural Sequence Model သည်
#   စာလုံးအကြီး/အသေး (A-Z, a-z)၊ Space၊ စာကြောင်းဆင်း (\n) နှင့် ပုဒ်ဖြတ်ပုဒ်ရပ် (.,;:'"?!)
#   အားလုံးကို တစ်လုံးချင်းစီ ဖတ်ရှုသင်ယူသည်။ ထို့ကြောင့် မော်ဒယ်သည် အဘိဓာန်မပါဘဲ
#   စာလုံးပေါင်းသတ်ပုံ (Morphology) နှင့် ဝါကျဖွဲ့စည်းပုံ (Syntax) ကို ကိုယ်တိုင်တည်ဆောက်နိုင်သည်။
# ==============================================================================
def load_author_raw_text(book_dir, max_chars=260000):
    """Books/English အောက်ရှိ စာသားအများဆုံး စာရေးဆရာ၏ စာအုပ်များကို ဖတ်ယူသည်"""
    eng_dir = os.path.join(book_dir, "English")
    if not os.path.isdir(eng_dir):
        first_lang = sorted([d for d in os.listdir(book_dir) if os.path.isdir(os.path.join(book_dir, d))])[0]
        eng_dir = os.path.join(book_dir, first_lang)

    author_texts = {}
    for author in sorted(os.listdir(eng_dir)):
        author_path = os.path.join(eng_dir, author)
        if not os.path.isdir(author_path):
            continue
        chunks = []
        for title in sorted(os.listdir(author_path)):
            if title.lower().endswith(".txt"):
                fp = os.path.join(author_path, title)
                with open(fp, "r", encoding="utf-8", errors="replace") as f:
                    chunks.append(f.read())
        if chunks:
            full_str = "\n".join(chunks)
            # စာကြောင်းလွတ် အများအပြားကို သပ်ရပ်အောင် ချုံ့ခြင်း
            full_str = "\n".join(line.strip() for line in full_str.splitlines() if line.strip())
            author_texts[author.capitalize()] = full_str

    best_author = max(author_texts.keys(), key=lambda a: len(author_texts[a]))
    text = author_texts[best_author][:max_chars]
    print(f"Selected Author: '{best_author}' | Using {len(text):,} characters for Neural Sequence Modeling.")
    return best_author, text


class CharSequenceDataset(Dataset):
    """စာသားရှည်ကို အလျား seq_len ရှိသော Input (x_t) နှင့် Next-Char Target (x_{t+1}) အတွဲများ ခွဲထုတ်သည်"""
    def __init__(self, encoded_ids, seq_len=100):
        self.data = torch.tensor(encoded_ids, dtype=torch.long)
        self.seq_len = seq_len

    def __len__(self):
        return (len(self.data) - 1) // self.seq_len

    def __getitem__(self, idx):
        start = idx * self.seq_len
        x = self.data[start:start + self.seq_len]
        y = self.data[start + 1:start + self.seq_len + 1]
        return x, y


# ==============================================================================
# အပိုင်း (၂) - Neural Sequence Model Architecture (Vanilla RNN vs. LSTM)
# AIMA (4th Ed.) Ch. 24, Sec. 24.2 (Recurrent Architectures, Cell State & Gates)
# သီအိုရီ -
#   1. Embedding Layer (nn.Embedding): အက္ခရာတစ်လုံးချင်းစီ၏ Index ကို Dense Vector
#      (embed_dim = 64) အဖြစ် ပြောင်းလဲပေးသဖြင့် သရအက္ခရာ (a,e,i,o,u) နှင့် ဗျည်းအက္ခရာများ၏
#      အဓိပ္ပာယ်ဆင်တူမှုကို စတင်ဖမ်းယူနိုင်သည်။
#   2. Recurrent Core (nn.RNN vs. nn.LSTM):
#      - Vanilla RNN သည် tanh(W_hh h_{t-1} + W_xh x_t) တစ်ခုတည်းကိုသာ သုံးသဖြင့်
#        Vanishing Gradient ကြောင့် စာကြောင်းရှည် မှတ်ဉာဏ် အားနည်းသည်။
#      - LSTM သည် Forget Gate (f_t), Input Gate (i_t), Cell State (c_t) နှင့် Output Gate (o_t)
#        တို့ကို သုံး၍ အတိတ်မှ အရေးကြီးအချက်အလက်များကို မပျောက်ပျက်ဘဲ ထိန်းသိမ်းပေးသည်။
# ==============================================================================
class NeuralCharLM(nn.Module):
    def __init__(self, vocab_size, embed_dim=64, hidden_dim=192, num_layers=2, cell_type="LSTM", dropout=0.2):
        super().__init__()
        self.cell_type = cell_type
        self.hidden_dim = hidden_dim
        self.num_layers = num_layers

        self.embedding = nn.Embedding(vocab_size, embed_dim)
        if cell_type == "LSTM":
            self.rnn = nn.LSTM(
                embed_dim, hidden_dim, num_layers=num_layers,
                dropout=dropout if num_layers > 1 else 0.0, batch_first=True
            )
        else:
            self.rnn = nn.RNN(
                embed_dim, hidden_dim, num_layers=num_layers, nonlinearity="tanh",
                dropout=dropout if num_layers > 1 else 0.0, batch_first=True
            )
        self.fc_out = nn.Linear(hidden_dim, vocab_size)

    def forward(self, x, hidden=None):
        emb = self.embedding(x)               # (Batch, Seq_Len, Embed_Dim)
        out, hidden = self.rnn(emb, hidden)   # (Batch, Seq_Len, Hidden_Dim)
        logits = self.fc_out(out)             # (Batch, Seq_Len, Vocab_Size)
        return logits, hidden


# ==============================================================================
# အပိုင်း (၃) - BPTT Training Loop (Gradient Clipping) & Temperature Sampling
# AIMA (4th Ed.) Ch. 24, Sec. 24.2 (Exploding Gradient Clipping & Softmax Temperature)
# ==============================================================================
def train_sequence_model(model, train_loader, val_loader, epochs=10, lr=0.003):
    model.to(DEVICE)
    optimizer = torch.optim.Adam(model.parameters(), lr=lr)
    criterion = nn.CrossEntropyLoss()

    train_losses, val_losses, val_ppls = [], [], []

    for ep in range(1, epochs + 1):
        model.train()
        total_tr_loss = 0.0
        for x_batch, y_batch in train_loader:
            x_batch, y_batch = x_batch.to(DEVICE), y_batch.to(DEVICE)
            optimizer.zero_grad()

            logits, _ = model(x_batch)
            loss = criterion(logits.reshape(-1, logits.size(-1)), y_batch.reshape(-1))
            loss.backward()

            # AIMA Sec. 24.2: Exploding Gradient ပြဿနာကို ကာကွယ်ရန် Gradient Norm ကို 1.0 ၌ ဖြတ်တောက်ခြင်း
            nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
            optimizer.step()
            total_tr_loss += loss.item()

        avg_tr_loss = total_tr_loss / len(train_loader)

        # Validation Set အပေါ် Cross-Entropy Loss နှင့် Character Perplexity တွက်ချက်ခြင်း
        model.eval()
        total_val_loss = 0.0
        with torch.no_grad():
            for x_val, y_val in val_loader:
                x_val, y_val = x_val.to(DEVICE), y_val.to(DEVICE)
                v_logits, _ = model(x_val)
                v_loss = criterion(v_logits.reshape(-1, v_logits.size(-1)), y_val.reshape(-1))
                total_val_loss += v_loss.item()

        avg_val_loss = total_val_loss / len(val_loader)
        char_perplexity = math.exp(avg_val_loss)

        train_losses.append(avg_tr_loss)
        val_losses.append(avg_val_loss)
        val_ppls.append(char_perplexity)

    return train_losses, val_losses, val_ppls


def generate_text_with_temperature(model, seed_str, char2idx, idx2char, length=240, temperature=0.75):
    """
    Temperature-Scaled Softmax Sampling:
      P(c_i) = exp(z_i / tau) / Sum_j exp(z_j / tau)
    """
    model.eval()
    valid_seed = [c for c in seed_str if c in char2idx]
    if not valid_seed:
        valid_seed = [idx2char[0]]

    input_ids = torch.tensor([[char2idx[c] for c in valid_seed]], dtype=torch.long, device=DEVICE)
    hidden = None
    generated_chars = list(valid_seed)

    with torch.no_grad():
        # Seed စာသားတစ်လျှောက် Hidden State ကို အရင်တည်ဆောက်ခြင်း (Warm-up)
        if input_ids.size(1) > 1:
            _, hidden = model(input_ids[:, :-1], hidden)
        curr_token = input_ids[:, -1:]

        for _ in range(length):
            logits, hidden = model(curr_token, hidden)
            scaled_logits = logits[:, -1, :] / max(temperature, 1e-4)
            probs = torch.softmax(scaled_logits, dim=-1)
            next_id = torch.multinomial(probs, num_samples=1)
            next_char = idx2char[next_id.item()]
            generated_chars.append(next_char)
            curr_token = next_id

    return "".join(generated_chars)


# ==============================================================================
# အပိုင်း (၄) - လက်တွေ့မောင်းနှင်ခြင်း (Vanilla RNN vs. LSTM ယှဉ်ပြိုင်စမ်းသပ်မှု)
# ==============================================================================
author_name, raw_text = load_author_raw_text(BOOK_DIR, max_chars=260000)

chars = sorted(list(set(raw_text)))
vocab_size = len(chars)
char2idx = {ch: i for i, ch in enumerate(chars)}
idx2char = {i: ch for i, ch in enumerate(chars)}
print(f"Character Vocabulary Size |V|: {vocab_size} unique characters (letters, case, punctuation, newlines)\n")

encoded_all = [char2idx[ch] for ch in raw_text]
split_pos = int(0.85 * len(encoded_all))
train_ds = CharSequenceDataset(encoded_all[:split_pos], seq_len=100)
val_ds = CharSequenceDataset(encoded_all[split_pos:], seq_len=100)

train_loader = DataLoader(train_ds, batch_size=64, shuffle=True, drop_last=True)
val_loader = DataLoader(val_ds, batch_size=64, shuffle=False, drop_last=True)

EPOCHS = 10
print(f"Training Vanilla RNN vs. LSTM on '{author_name}' ({EPOCHS} Epochs, Device={DEVICE})...")

t0 = time.time()
rnn_model = NeuralCharLM(vocab_size, embed_dim=64, hidden_dim=192, num_layers=2, cell_type="RNN")
rnn_tr, rnn_val, rnn_ppl = train_sequence_model(rnn_model, train_loader, val_loader, epochs=EPOCHS, lr=0.0025)
t_rnn = time.time() - t0

t1 = time.time()
lstm_model = NeuralCharLM(vocab_size, embed_dim=64, hidden_dim=192, num_layers=2, cell_type="LSTM")
lstm_tr, lstm_val, lstm_ppl = train_sequence_model(lstm_model, train_loader, val_loader, epochs=EPOCHS, lr=0.0035)
t_lstm = time.time() - t1

print("=" * 84)
print(f"NEURAL SEQUENCE MODEL BENCHMARK ({author_name} — Character-Level Prediction)")
print("-" * 84)
print(f"  1. Vanilla RNN (2-Layer tanh) -> Final Val Loss: {rnn_val[-1]:.4f} | Char Perplexity: {rnn_ppl[-1]:5.2f} ({t_rnn:.1f}s)")
print(f"  2. LSTM        (2-Layer Gate) -> Final Val Loss: {lstm_val[-1]:.4f} | Char Perplexity: {lstm_ppl[-1]:5.2f} ({t_lstm:.1f}s)")
print("=" * 84 + "\n")

# --- Temperature-Controlled Text Generation Samples ---
seed_prompt = raw_text[:45].split("\n")[0][:30]
if len(seed_prompt) < 10:
    seed_prompt = "The king said unto him, "

print("=" * 84)
print(f"LSTM SYNTHETIC TEXT GENERATION ACROSS SOFTMAX TEMPERATURES (Seed: {repr(seed_prompt)})")
print("-" * 84)
for tau, desc in [
    (0.40, "Low Temp (τ = 0.40 — Conservative, High Spelling Precision)"),
    (0.75, "Balanced Temp (τ = 0.75 — Natural Literary Rhythm & Syntax)"),
    (1.15, "High Temp (τ = 1.15 — High Entropy, Creative / Risky)")
]:
    sample_out = generate_text_with_temperature(
        lstm_model, seed_prompt, char2idx, idx2char, length=210, temperature=tau
    ).replace("\n", " ")
    print(f"[{desc}]")
    print(f"  \"{sample_out}\"\n")
print("=" * 84)


# ==============================================================================
# အပိုင်း (၅) - ရလဒ်ဂရပ်ဖ် ၂ ခု ရေးဆွဲခြင်း
#   Figure 1: Vanilla RNN vs. LSTM Validation Loss & Character Perplexity Curves
#   Figure 2: LSTM Internal Hidden State Activations & Learned Character Embeddings (PCA)
# ==============================================================================
fig1, (ax1, ax2) = plt.subplots(1, 2, figsize=(15.5, 5.6))
ep_axis = np.arange(1, EPOCHS + 1)

# Left: Cross-Entropy Loss Comparison
ax1.plot(ep_axis, rnn_val, "o--", color="#e67e22", linewidth=2.2, label=f"Vanilla RNN (Val Loss={rnn_val[-1]:.3f})")
ax1.plot(ep_axis, lstm_val, "s-", color="#16a085", linewidth=2.5, label=f"LSTM Gated Memory (Val Loss={lstm_val[-1]:.3f})")
ax1.set_xticks(ep_axis)
ax1.set_xlabel("Training Epoch", fontsize=11, fontweight="bold")
ax1.set_ylabel("Validation Cross-Entropy Loss (Nats)", fontsize=11, fontweight="bold")
ax1.set_title("1. Vanilla RNN vs. LSTM Learning Curve\n(LSTM Cell State Overcomes Vanishing Gradients)",
              fontsize=11.5, fontweight="bold")
ax1.legend(fontsize=9.5)

# Right: Character Perplexity Comparison
ax2.plot(ep_axis, rnn_ppl, "o--", color="#e67e22", linewidth=2.2, label=f"Vanilla RNN (PP={rnn_ppl[-1]:.2f} chars)")
ax2.plot(ep_axis, lstm_ppl, "s-", color="#2980b9", linewidth=2.5, label=f"LSTM (PP={lstm_ppl[-1]:.2f} chars)")
ax2.set_xticks(ep_axis)
ax2.set_xlabel("Training Epoch", fontsize=11, fontweight="bold")
ax2.set_ylabel("Character Perplexity exp(Loss) [Lower = Better]", fontsize=11, fontweight="bold")
ax2.set_title("2. Character-Level Perplexity Reduction\n(Effective Next-Character Branching Factor)",
              fontsize=11.5, fontweight="bold")
ax2.legend(fontsize=9.5)

plt.tight_layout()
plt.show()

# --- Figure 2: Internal LSTM Hidden Unit Dynamics & Learned Character Embedding Map ---
probe_sentence = 'He said, "Upon my word, I shall return!"'
probe_valid = [c for c in probe_sentence if c in char2idx]
probe_tensor = torch.tensor([[char2idx[c] for c in probe_valid]], dtype=torch.long, device=DEVICE)

lstm_model.eval()
with torch.no_grad():
    emb_p = lstm_model.embedding(probe_tensor)
    top_hidden_seq, _ = lstm_model.rnn(emb_p)  # (1, T, hidden_dim)
    h_np = top_hidden_seq.squeeze(0).cpu().numpy()  # (T, hidden_dim)

# အချိန်အလိုက် အပြောင်းအလဲ အများဆုံး (Highest Variance) LSTM Hidden Neurons ၁၂ ခုကို ရွေးထုတ်ခြင်း
unit_vars = np.var(h_np, axis=0)
top_units = np.argsort(unit_vars)[-12:][::-1]
h_sub = h_np[:, top_units].T  # (12, T)

fig2, (ax3, ax4) = plt.subplots(1, 2, figsize=(16.5, 5.8), gridspec_kw={"width_ratios": [1.45, 1]})

im = ax3.imshow(h_sub, aspect="auto", cmap="RdBu_r", vmin=-1.0, vmax=1.0)
ax3.set_xticks(np.arange(len(probe_valid)))
ax3.set_xticklabels([repr(c).strip("'") if c != " " else "␣" for c in probe_valid], fontsize=9, fontweight="bold")
ax3.set_yticks(np.arange(len(top_units)))
ax3.set_yticklabels([f"Unit #{u}" for u in top_units], fontsize=8.5)
ax3.grid(False)
plt.colorbar(im, ax=ax3, fraction=0.035, pad=0.03, label="Hidden State Activation h_t ∈ [-1, 1]")
ax3.set_title("1. Internal LSTM Hidden State Activations Across a Sentence\n(Neurons Dynamically Track Quotes, Word Boundaries '␣' & Clauses)",
              fontsize=11, fontweight="bold")

# Right: 2D PCA of Learned Character Embeddings (Vowels vs. Consonants vs. Punctuation)
emb_weights = lstm_model.embedding.weight.detach().cpu().numpy()
target_chars = [c for c in "aeiouAEIOUbcdfghjklmnpqrstvwxyz.,;!?\"' " if c in char2idx]
target_ids = [char2idx[c] for c in target_chars]
emb_2d = PCA(n_components=2, random_state=42).fit_transform(emb_weights[target_ids])

for idx_c, ch in enumerate(target_chars):
    if ch in "aeiouAEIOU":
        col, grp_lbl = "#c0392b", "Vowels"
    elif ch in ".,;!?\"' ":
        col, grp_lbl = "#16a085", "Punctuation & Space"
    else:
        col, grp_lbl = "#2980b9", "Consonants"
    ax4.scatter(emb_2d[idx_c, 0], emb_2d[idx_c, 1], color=col, s=65, alpha=0.88)
    disp_ch = "SPACE" if ch == " " else ch
    ax4.annotate(disp_ch, (emb_2d[idx_c, 0], emb_2d[idx_c, 1]), xytext=(4, 3),
                 textcoords="offset points", fontsize=9, fontweight="bold", color=col)

ax4.set_title("2. 2D PCA of Learned Character Embeddings (nn.Embedding)\n(Red: Vowels | Blue: Consonants | Teal: Punctuation/Space)",
              fontsize=11, fontweight="bold")
ax4.set_xlabel("Principal Component 1")
ax4.set_ylabel("Principal Component 2")

plt.tight_layout()
plt.show()


၃။ ထွက်ပေါ်လာမည့် ရလဒ်များမှ တွေ့ရှိရမည့် အရေးကြီး အချက် ၃ ချက်

  1. Vanilla RNN ထက် LSTM ၏ သာလွန်မှု (Figure 1 — Loss & Perplexity Curves):

    • Parameter အရေအတွက်နှင့် လေ့ကျင့်ချိန် တူညီသည့်တိုင် LSTM သည် Cell State ($\mathbf{c}_t$) နှင့် Forget/Input Gates များကြောင့် Validation Cross-Entropy Loss ပိုမိုကျဆင်းပြီး Character Perplexity (~4.5 – 5.5 characters အထိ) သိသိသာသာ နိမ့်ကျသည်ကို တွေ့ရပါမည်။

  2. အတွင်းပိုင်း LSTM Neuron များ၏ မှတ်ဉာဏ်ခြေရာခံမှု (Figure 2 — ဘယ်ဘက် Heatmap):

    • ဝါကျတစ်ကြောင်းကို တစ်လုံးချင်း ဖတ်ရှုသွားချိန်တွင် အချို့သော LSTM Hidden Units များသည် Space (␣) နေရာရောက်တိုင်း အနီရောင်/အပြာရောင် ပြောင်းလဲ၍ စကားလုံးအစအဆုံးကို ရေတွက်ပေးနေပြီး၊ အချို့ Units များမှာ မျက်တောင်အဖွင့် (") မှ မျက်တောင်အပိတ် (") ရောက်သည်အထိ တောက်လျှောက် တက်ကြွနေသည် (Quote-Tracking Cell) ကို မျက်မြင်တွေ့ရှိနိုင်ပါသည်။

  3. သရ၊ ဗျည်းနှင့် ပုဒ်ဖြတ်ပုဒ်ရပ်များ အလိုအလျောက် အုပ်စုဖွဲ့ခြင်း (Figure 2 — ညာဘက် PCA Map):

    • အက္ခရာများ၏ ဘာသာဗေဒအမျိုးအစားကို လုံးဝမသင်ကြားထားသော်လည်း nn.Embedding အလွှာသည် သရအက္ခရာများ (a, e, i, o, u)၊ ဗျည်းအက္ခရာများ နှင့် ပုဒ်ဖြတ်ပုဒ်ရပ်များ (. , ; ! ?) ကို Vector Space ပေါ်တွင် သီးခြားအစုအဝေးများအဖြစ် အလိုအလျောက် ခွဲခြားစုစည်းပေးထားသည်ကို တွေ့မြင်နိုင်ပါသည်။