Wednesday, November 18, 2026

Optical Recognition of Handwritten Digits by Support Vector Machine

အခုလေ့လာမဲ့ ပရိုဂရမ်က UCI Machine Learning Repository က လက်ရေးဂဏန်းပုံရိပ် ဒေတာ (optdigits.tra နဲ့optdigits.tes) တွေကို Support Vector Machine (SVC) အသုံးပြုပြီး ခွဲခြားခန့်မှန်းတဲ့ ပရိုဂရမ်ဖြစ်ပါတယ်။


အဆင့်တစ်ခုချင်းစီ၏ ရှင်းလင်းချက်

  • TODO 1 (ဒေတာဖတ်ယူခြင်းနှင့် load() ဖန်ရှင်) .tes (Testing) နှင့် .tra (Training) ဖိုင်နှစ်ခုကို ဖတ်ယူ၍ ရှေ့ဆုံးကော်လံ ၆၄ ခု (0 မှ 63) ကို Pixel Features (X) အဖြစ်လည်းကောင်း၊ နောက်ဆုံးကော်လံ (64) ကို အဖြေမှန်ဂဏန်း (y) အဖြစ်လည်းကောင်း ခွဲထုတ်ပေးရပါမည်။

  • TODO 2 & 3 (USPS 98% စံချိန်ကို ကျော်ဖြတ်ခြင်း — linear vs poly vs rbf)

    • USPS စာတိုက်ဌာန၏ လက်ရေးဂဏန်းခွဲခြားမှု စံချိန်ဖြစ်သော 98.0% ကို ကျော်ဖြတ်နိုင်ရန် SVC Kernel များကို စမ်းသပ်ခိုင်းထားပါသည်။

      • kernel='linear' (C=1): ~96.10% သာ ရရှိသဖြင့် 98% မပြည့်မီပါ (လက်ရေးမျဉ်းကွေးများကို မျဉ်းဖြောင့်တစ်ကြောင်းတည်းဖြင့် ခွဲခြားရန် ခက်ခဲသောကြောင့် ဖြစ်သည်)။

      • kernel='poly' (C=1, gamma=0.001 သို့မဟုတ် degree=3): ~97.8% – 98.1% ဝန်းကျင် ရရှိပါသည်။

      • kernel='rbf' (C=1, gamma=0.001): 98.27% အထိ ရရှိပြီး USPS ၏ 98% စံချိန်ကို အောင်မြင်စွာ ကျော်ဖြတ်နိုင်ပါသည်။

  • TODO 4 (၁၀၀၀ ခုမြောက် Test ပုံရိပ် index = 999 ကို စစ်ဆေးခြင်း)

    • Python တွင် Index သည် 0 မှ စတင်သောကြောင့် ၁၀၀၀ ခုမြောက်ပုံရိပ်မှာ index = 999 ဖြစ်ပါသည်။ y_test[999] နှင့် svc.predict(X_test.iloc[[999]])[0] တို့ကို နှိုင်းယှဉ်ပြီး imshow ဖြင့် ပုံရိပ်ကို ကြည့်ရှုစစ်ဆေးရပါမည်။

  • TODO 5 (# Special: — Training Data ၏ ရှေ့ဆုံး 4% ကိုသာ ချန်ထားပြီး 96% ကို ဖယ်ထုတ်ခြင်း)

    • Training Data စုစုပေါင်း 3,823 ခု၏ 4% မှာ 3823 × 0.04 = 152.92 ဖြစ်သဖြင့် int(math.ceil(...)) သုံးသောအခါ 153 ခု သာ ကျန်ရှိပါမည် (ဂဏန်း ၁ မျိုးလျှင် ပျမ်းမျှ ၁၅ ပုံခန့်သာ ရှိတော့သည်)။

    • အံ့အားသင့်ဖွယ် ရလဒ် (rbf vs linear on 4% Data)

      • ဒေတာ 96% ကို လွှင့်ပစ်လိုက်သောအခါ kernel='rbf' (gamma=0.001) ၏ တိကျမှုသည် 98.27% မှ ~85% – 88% ဝန်းကျင်အထိ သိသိသာသာ ထိုးကျသွားပါမည်။

      • သို့သော် kernel='linear' သို့ ပြန်ပြောင်းလိုက်သောအခါ တိကျမှုသည် ~91% – 93% အထိ ပြန်လည်မြင့်တက်လာပြီး rbf ထက် ပိုမိုကောင်းမွန်နေသည်ကို အံ့အားသင့်ဖွယ် တွေ့ရပါမည်။ (အကြောင်းရင်းကို AIMA သီအိုရီဖြင့် အောက်တွင် ရှင်းပြထားပါသည်။)

၃။ Python Code

အောက်ပါ ပရိုဂရမ်တွင် TODO အားလုံးကို တစ်ဆက်တည်း ကြည့်ရှုနိုင်စေရန် Full Dataset Experiment (100% Data) နှင့် # Special: (4% Data) Experiment နှစ်ခုလုံးကို စနစ်တကျ ထည့်သွင်းရေးသားထားပါသည်။

Python
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.svm import SVC

plt.style.use('ggplot')

# ==============================================================================
# အပိုင်း (၁) - Dataset ဖတ်ယူခြင်းနှင့် # Special: (4% Training Data Slicing)
# AIMA (4th Ed.) Ch. 25, Sec. 25.1 (Computer Vision: Image Preprocessing & Downsampling)
# AIMA (4th Ed.) Ch. 19, Sec. 19.2 & 19.4 (Sample Complexity & Learning Curves)
# သီအိုရီ -
# 1. UCI optdigits ဒေတာသည် မူလ 32x32 ဘစ်ပုံရိပ်များကို 8x8 အကွက်ငယ်များအဖြစ်
# ပျမ်းမျှယူ ချုံ့ထားခြင်း (Spatial Downsampling) ဖြစ်ပြီး Pixel တစ်ခုစီတွင် မီးခိုးရောင်
# အနုအရင့်တန်ဖိုး (0 မှ 16 အထိ) ပါဝင်သဖြင့် Feature ၆၄ ခု (64D Space) ရှိသည်။
# 2. # Special: Training Data ၏ ရှေ့ဆုံး 4% (153 samples) ကိုသာ ချန်ထားခြင်းဖြင့်
# နမူနာဒေတာ နည်းပါးချိန် (Small Sample Regime) တွင် မော်ဒယ်များ၏ Generalization
# မည်သို့ ပြောင်းလဲသွားသည်ကို စမ်းသပ်နိုင်သည်။
# ==============================================================================
def load(path_test, path_train, train_keep_ratio=1.0):
# header=None ထည့်ပေးမှသာ ပထမဆုံး ဂဏန်းပုံရိပ်ဒေတာ ၁ ကြောင်း မဆုံးရှုံးဘဲ အပြည့်အဝ ရရှိမည်
testing = pd.read_csv(path_test, header=None)
training = pd.read_csv(path_train, header=None)

n_features = testing.shape[1] # စုစုပေါင်း 65 columns (0..63 = pixels, 64 = digit label)

# Deprecated ဖြစ်သွားသော .ix အစား .iloc ကို အသုံးပြုခြင်း
X_test = testing.iloc[:, :n_features - 1]
X_train = training.iloc[:, :n_features - 1]
y_test = testing.iloc[:, n_features - 1].to_numpy().ravel()
y_train = training.iloc[:, n_features - 1].to_numpy().ravel()

# Special: Training Data ၏ ရှေ့ဆုံး သတ်မှတ်ရာခိုင်နှုန်း (ဥပမာ 4%) ကိုသာ ဖြတ်ယူခြင်း
if train_keep_ratio < 1.0:
n_keep = int(math.ceil(train_keep_ratio * len(X_train)))
X_train = X_train.iloc[:n_keep, :]
y_train = y_train[:n_keep]

return X_train, X_test, y_train, y_test

# ==============================================================================
# အပိုင်း (၂) - Training ဒေတာထဲမှ ပထမဆုံး ပုံရိပ် ၅၀ ကို ကြည့်ရှုစစ်ဆေးခြင်း
# ==============================================================================
def peekData(X_train):
print("Peeking your data (First 50 training digits)...")
fig = plt.figure(figsize=(10, 5))

cnt = 0
for row in range(5):
for col in range(10):
plt.subplot(5, 10, cnt + 1)
# Pandas Series ကို NumPy Array ပြောင်းပြီးမှ 8x8 2D ပုံရိပ်အဖြစ် ပြန်စီခြင်း
img_8x8 = X_train.iloc[cnt, :].to_numpy().reshape(8, 8)
plt.imshow(img_8x8, cmap=plt.cm.gray_r, interpolation='nearest')
plt.axis('off')
cnt += 1

plt.suptitle('Sample 8x8 Handwritten Digits from Training Set (optdigits.tra)', fontsize=12, fontweight='bold')
plt.tight_layout()
plt.show()

# ==============================================================================
# အပိုင်း (၃) - Test ဒေတာ ပထမဆုံး ပုံရိပ် ၅၀ အပေါ် SVC ၏ ခန့်မှန်းချက်များကို ပုံဖော်စစ်ဆေးခြင်း
# (အစိမ်းရောင် = အဖြေမှန်၊ အနီရောင် = အဖြေမှား)
# ==============================================================================
def drawPredictions(model, X_test, y_test, title_suffix=""):
fig = plt.figure(figsize=(11, 5.5))
y_guess = model.predict(X_test)

num_rows = 5
num_cols = 10

index = 0
for row in range(num_rows):
for col in range(num_cols):
plt.subplot(num_rows, num_cols, index + 1)
img_8x8 = X_test.iloc[index, :].to_numpy().reshape(8, 8)
plt.imshow(img_8x8, cmap=plt.cm.gray_r, interpolation='nearest')

fontcolor = 'green' if y_test[index] == y_guess[index] else 'red'
plt.title(f'Pred: {y_guess[index]} (T:{y_test[index]})', fontsize=7, color=fontcolor)
plt.axis('off')
index += 1

plt.suptitle(f'SVC Predictions on First 50 Test Digits {title_suffix}\n(Green = Correct, Red = Misclassified)',
fontsize=11.5, fontweight='bold')
plt.tight_layout()
plt.show()

# ==============================================================================
# အပိုင်း (၄) - ဒေတာဖတ်ယူခြင်း (Raw String r'...' ဖြင့် Windows Path Error ကို ကာကွယ်ထားသည်)
# ==============================================================================
path_tes = r'C:\Users\kks\OneDrive\Desktop\MyPyTest\Module4\Datasets\optdigits.tes'
path_tra = r'C:\Users\kks\OneDrive\Desktop\MyPyTest\Module4\Datasets\optdigits.tra'

X_train, X_test, y_train, y_test = load(path_tes, path_tra, train_keep_ratio=1.0)
print(f"Full Dataset Loaded -> X_train: {X_train.shape}, X_test: {X_test.shape}\n")

# ပထမဆုံး Training ပုံရိပ် ၅၀ ကို ကြည့်ရှုခြင်း
peekData(X_train)

# ==============================================================================
# အပိုင်း (၅) - Support Vector Machine (SVC) & Kernel Trick စမ်းသပ်မှု
# AIMA (4th Ed.) Ch. 19, Sec. 19.7 (Support Vector Machines & The Kernel Trick)
# သီအိုရီ -
# 1. Maximum Margin Hyperplane: SVM သည် မတူညီသော ဂဏန်းအတန်းအစားများကြားရှိ
# နယ်နိမိတ်မျဉ်း (Decision Boundary) ကို အနီးဆုံးဒေတာအမှတ်များ (Support Vectors) နှင့်
# အကွာအဝေး အကျယ်ဆုံး (Maximum Margin) ဖြစ်အောင် ရှာဖွေပေးခြင်းဖြင့် Overfitting ကို လျှော့ချသည်။
# 2. Kernel Trick K(x_i, x_j) = phi(x_i) . phi(x_j): မူလ 64D Pixel များကို ပိုမိုမြင့်မားသော
# Dimension (High-Dimensional Feature Space) သို့ တိုက်ရိုက်မပြောင်းဘဲ အတွင်းမြှောက်လဒ်
# (Inner Product) ဖြင့်သာ တွက်ချက်ပေးသည်။
# - Linear Kernel: K(x, x') = x . x' (မျဉ်းဖြောင့်နယ်နိမိတ်)
# - Polynomial Kernel: K(x, x') = (gamma * (x . x') + r)^d (ကွေးညွှတ်သော နယ်နိမိတ်)
# - RBF (Gaussian) Kernel: K(x, x') = exp(-gamma * ||x - x'||^2) (အနန္တ Dimension)
# ==============================================================================
print("=" * 75)
print("EXPERIMENT 1: Full Training Data (100% = 3,823 samples) — Beating USPS 98% Benchmark")
print("-" * 75)

for kern in ['linear', 'poly', 'rbf']:
clf = SVC(kernel=kern, C=1.0, gamma=0.001)
clf.fit(X_train, y_train)
acc = clf.score(X_test, y_test)
beat_usps = "BEATS USPS 98%!" if acc > 0.98 else "Below 98%"
print(f" SVC (kernel='{kern:<6}', C=1, gamma=0.001) -> Test Accuracy: {acc * 100:6.2f}% [{beat_usps}]")

# USPS 98% စံချိန်ကို ကျော်ဖြတ်နိုင်သော RBF SVC မော်ဒယ်ကို အဓိကမော်ဒယ်အဖြစ် လေ့ကျင့်ခြင်း
print("\nTraining Optimal RBF SVC Classifier...")
svc = SVC(kernel='rbf', C=1.0, gamma=0.001)
svc.fit(X_train, y_train)
score = svc.score(X_test, y_test)
print(f"Optimal RBF SVC Score: {score:.4f} ({score * 100:.2f}%)\n")

# ပထမဆုံး Test ပုံရိပ် ၅၀ ၏ ခန့်မှန်းချက်များကို ပုံဖော်ကြည့်ရှုခြင်း
drawPredictions(svc, X_test, y_test, title_suffix=f"[RBF Kernel | Acc: {score*100:.2f}%]")

# ==============================================================================
# အပိုင်း (၆) - ၁၀၀၀ ခုမြောက် Test ပုံရိပ် (Index = 999) ကို အသေးစိတ် စစ်ဆေးခြင်း
# ==============================================================================
idx_1000 = 999
true_label_1000 = y_test[idx_1000]
# DataFrame တစ်ကြောင်းတည်းကို 2D Shape (1, 64) အတိုင်း iloc[[idx_1000]] ဖြင့် ထည့်ပေးရမည်
pred_label_1000 = svc.predict(X_test.iloc[[idx_1000]])[0]

print("=" * 75)
print(f"1000th Test Sample Inspection (Index {idx_1000}):")
print(f" 1000th test TRUE label : {true_label_1000}")
print(f" 1000th test SVC prediction : {pred_label_1000}")
print(f" Prediction Correct? : {true_label_1000 == pred_label_1000}")
print("=" * 75)

# ၁၀၀၀ ခုမြောက် ပုံရိပ်ကို မျက်စိဖြင့် ကြည့်ရှုစစ်ဆေးခြင်း (imshow)
plt.figure(figsize=(3.5, 3.5))
plt.imshow(X_test.iloc[idx_1000].to_numpy().reshape(8, 8), cmap=plt.cm.gray_r, interpolation='nearest')
plt.title(f'1000th Test Image (Index 999)\nTrue: {true_label_1000} | Predicted: {pred_label_1000}',
fontsize=11, fontweight='bold',
color='green' if true_label_1000 == pred_label_1000 else 'red')
plt.axis('off')
plt.tight_layout()
plt.show()

# ==============================================================================
# အပိုင်း (၇) - # Special: Training Data ၏ ရှေ့ဆုံး 4% (96% ဖယ်ထုတ်ပြီး) စမ်းသပ်ချက်
# AIMA (4th Ed.) Ch. 19, Sec. 19.3 & 19.4 (Inductive Bias, VC Dimension & Small Sample Regime)
# သီအိုရီ -
# Training Data 96% ကို ဖယ်ထုတ်လိုက်သောအခါ ကျန်ရှိသော 4% (153 samples) တွင် ဂဏန်း ၁ မျိုးလျှင်
# ၁၅ ပုံခန့်သာ ရှိတော့သည်။
# - RBF Kernel သည် Local Support Vectors များအပေါ် မှီခိုသဖြင့် ဒေတာကျဲသွားသောအခါ
# အကွက်လပ်များ ဖြစ်ပေါ်ပြီး တိကျမှု သိသိသာသာ ကျဆင်းသွားသည် (High Variance)။
# - Linear Kernel သည် 64D Space တွင် အားကောင်းသော Inductive Bias (နိမ့်သော VC Dimension)
# ရှိသောကြောင့် ဒေတာနည်းပါးချိန်တွင် Overfitting နည်းပါးပြီး RBF ထက် ပိုတိကျနေသည်!
# ==============================================================================
X_train_4pct, X_test_4pct, y_train_4pct, y_test_4pct = load(path_tes, path_tra, train_keep_ratio=0.04)

print("\n" + "=" * 75)
print(f"EXPERIMENT 2 (# Special: First 4% Training Data Only = {len(X_train_4pct)} samples)")
print("-" * 75)

svc_rbf_4pct = SVC(kernel='rbf', C=1.0, gamma=0.001).fit(X_train_4pct, y_train_4pct)
score_rbf_4pct = svc_rbf_4pct.score(X_test_4pct, y_test_4pct)

svc_lin_4pct = SVC(kernel='linear', C=1.0, gamma=0.001).fit(X_train_4pct, y_train_4pct)
score_lin_4pct = svc_lin_4pct.score(X_test_4pct, y_test_4pct)

print(f" 4% Data -> SVC (kernel='rbf') Test Accuracy: {score_rbf_4pct * 100:6.2f}%")
print(f" 4% Data -> SVC (kernel='linear') Test Accuracy: {score_lin_4pct * 100:6.2f}% <-- Surprised? Linear beats RBF!")
print("=" * 75)


၄။ AIMA သီအိုရီ အနှစ်ချုပ်

"ဒေတာ 96% ကို ဖယ်ထုတ်ပြီး kernel='linear' သို့ ပြန်ပြောင်းလိုက်သောအခါ ထွက်လာသည့် ရလဒ်ကို အံ့အားသင့်သွားသလား (Surprised?)" ဆိုတဲ့ မေးခွန်းရဲ့ အဖြေဟာ AIMA Chapter 19, Section 19.3 (Model Selection / Inductive Bias) နဲ့ Section 19.4 (Learning Theory / VC Dimension) တို့ရဲ့ အနှစ်သာရပဲ ဖြစ်တယ်။

  • ဒေတာ များပြားချိန် (100% = 3,823 samples) ဂဏန်းတစ်ခုစီအတွက် နမူနာပေါင်း ၃၈၀ ခန့် ရှိနေသဖြင့် RBF Kernel သည် လက်ရေးပုံစံအမျိုးမျိုး၏ ကွေးညွှတ်မှု အသေးစိတ်ကို တိကျစွာ ပုံဖော်နိုင်ပြီး 98.27% အထိ ရရှိပါသည်။

  • ဒေတာ အလွန်နည်းပါးချိန် (4% = 153 samples) ဂဏန်းတစ်ခုစီအတွက် ၁၅ ပုံခန့်သာ ရှိတော့သောအခါ Flexible ဖြစ်လွန်းသော RBF Kernel သည် ထို ၁၅ ပုံဝန်းကျင်၌သာ အဝိုင်းလေးများ ဝိုင်းပတ်မိပြီး မမြင်ဖူးသော လက်ရေးပုံစံအသစ်များကို လွတ်သွားသဖြင့် ~86% သို့ ကျဆင်းသွားပါသည်။ ဆန့်ကျင်ဘက်အားဖြင့် ရိုးရှင်းသော Linear Kernel သည် ပြင်းထန်သော Inductive Bias (64D Space တွင် မျဉ်းပြားနယ်နိမိတ်) ရှိသောကြောင့် ဒေတာအနည်းငယ်မျှဖြင့်ပင် ဂဏန်းတစ်ခုစီ၏ ပင်မ Pixel တည်နေရာကို ယေဘုယျပြုနိုင်ပြီး ~92% အထိ ပိုမိုတိကျစွာ ခန့်မှန်းနိုင်ခြင်း ဖြစ်ပါသည်။

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.