ข้ามไปที่เนื้อหา

Master Generative AI — Part 1: พื้นฐาน AI & Machine Learning

นี่คือ Part 1 ของซีรีส์ Master Generative AI: A Step-by-Step Challenge — ไกด์สายลงมือทำ เน้นของจริง ไม่มีน้ำ พาคุณจากศูนย์ไปจนเป็น AI practitioner ที่ทำงานได้อย่างมั่นใจในปี 2026

แผนที่ซีรีส์:


AI ไม่ใช่เรื่องของนักวิจัยอย่างเดียวอีกแล้ว ปี 2026 นี้ tool, library และ model ที่เมื่อก่อนต้องจบดอกเตอร์และมีซูเปอร์คอมพิวเตอร์ถึงจะได้จับ ตอนนี้ developer คนไหนก็ใช้ได้ ขอแค่ยอมทุ่มเวลาเรียนจริงจังสักไม่กี่สัปดาห์ ซีรีส์นี้คือแผนที่ที่พาไปทีละขั้น

เราจะเริ่มกันตั้งแต่ศูนย์ ไม่ใช่เพราะคิดว่าคุณไม่เก่ง แต่เพราะ practitioner ที่เก่งจริงล้วนมีพื้นฐานแน่นทั้งนั้น


บทที่ 1: รู้จัก AI & Generative AI

Artificial Intelligence คืออะไร?

Artificial Intelligence คือการสร้างระบบให้ทำงานที่ปกติต้องใช้สมองคน เช่น ดูภาพแล้วบอกได้ว่าเป็นอะไร เข้าใจภาษา หรือตัดสินใจ

AI (the broad field)
│
├── Machine Learning (learns from data)
│   │
│   ├── Deep Learning (neural networks)
│   │   │
│   │   ├── NLP (language tasks)
│   │   ├── Computer Vision (image tasks)
│   │   └── Generative AI ← where we're going
│   │
│   └── Classical ML (trees, SVMs, linear models)
│
└── Symbolic AI (rules, logic, expert systems)

Generative AI คืออะไร?

ระบบ AI ส่วนใหญ่เป็นแบบ discriminative คือแยกประเภทหรือทำนายผล ส่งภาพเข้าไปหนึ่งภาพ ระบบก็ตอบว่า "แมว" หรือ "หมา"

Generative AI สร้างของใหม่ที่ไม่เคยมีมาก่อน ทั้ง text, ภาพ, เสียง, วิดีโอ และ code:

ประเภท ตัวอย่าง สร้างอะไรได้
Text GPT-4, Claude, Gemini บทความ, code, คำตอบ
Image Stable Diffusion, DALL-E ภาพถ่าย, งานศิลปะ, งานออกแบบ
Audio ElevenLabs, Whisper เสียงพูด, เพลง, เสียงประกอบ
Video Sora, Runway คลิป, animation
Code Copilot, Code Llama โปรแกรม, script
Multimodal GPT-4o, Gemini ผสมทุกแบบข้างบนได้หมด

ภาพรวม Generative AI ปี 2026

Foundation Models (trained on massive data, cost millions)
    GPT-4o    Claude 3.5/4    Gemini 2.0    LLaMA 3.1
         ↓ fine-tuning / prompt engineering ↓
Application Layer (your products and solutions)
    Chatbots  Code assistants  Content tools  AI agents

ประเด็นสำคัญ: คุณไม่ต้อง train foundation model เอง แค่ หยิบมาใช้ งานของ practitioner คือรู้ว่าควรเลือก model ตัวไหน เขียน prompt ยังไง เมื่อไหร่ถึงควร fine-tune และ deploy ยังไงให้ระบบนิ่ง


บทที่ 2: พื้นฐาน Machine Learning

Machine Learning คืออะไร?

เขียนโปรแกรมแบบเดิม: คุณเขียนกฎ → คอมพิวเตอร์ทำตาม Machine learning: คุณให้ตัวอย่าง → คอมพิวเตอร์หากฎเอง

# Traditional programming
def classify_email(email):
    if "FREE" in email and "CLICK HERE" in email:
        return "spam"
    return "not spam"

# Machine learning
# (the model learns these rules from 10,000 labeled examples)
model = train(emails, labels)
prediction = model.predict(new_email)

Supervised Learning

ป้อนข้อมูลที่ติด label ไว้แล้วให้ model แปลว่า input แต่ละตัวมีเฉลยกำกับมาด้วย แล้ว model จะเรียนว่า input แบบไหนควรได้ output อะไร

Data:
  (email_1, "spam")
  (email_2, "not spam")
  (email_3, "spam")
  ...

Model learns: features → label

Use cases: classification, regression, object detection
Examples: spam filter, house price prediction, medical diagnosis
# Example: Supervised learning with scikit-learn
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# Features: [size_sqm, bedrooms, distance_to_center]
X = [[85, 2, 3.2], [120, 3, 1.5], [45, 1, 8.0], [200, 4, 0.5]]
y = [4500000, 8000000, 2000000, 15000000]  # prices in THB

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
model = RandomForestClassifier()
model.fit(X_train, y_train)
predictions = model.predict(X_test)

Unsupervised Learning

ไม่มี label เลย model ต้องหา pattern และโครงสร้างที่ซ่อนอยู่ในข้อมูลเอง

Data:
  (customer_1_purchase_history)
  (customer_2_purchase_history)
  (customer_3_purchase_history)
  ...

Model discovers: natural groupings (clusters)

Use cases: clustering, dimensionality reduction, anomaly detection
Examples: customer segmentation, recommendation systems, fraud detection
# Example: K-means clustering
from sklearn.cluster import KMeans
import numpy as np

# Customer data: [monthly_spend, purchase_frequency]
customers = np.array([
    [500, 2], [600, 3], [5000, 15], [4800, 12],
    [200, 1], [100, 1], [5200, 18], [300, 2]
])

kmeans = KMeans(n_clusters=3, random_state=42)
kmeans.fit(customers)
print(kmeans.labels_)  # [0, 0, 1, 1, 2, 2, 1, 0] → 3 customer segments found

Reinforcement Learning

agent เรียนจากการลองทำ action ใน environment แล้วดูผลว่าได้ reward หรือโดน penalty

Agent → Action → Environment → Reward → Agent (update policy)

Examples: game playing (AlphaGo), robotics, RLHF for LLMs (ChatGPT)

ML Workflow (ใช้ได้ทุกงาน)

1. Define the problem     → What are we predicting?
2. Collect data           → More labeled data = better model
3. Explore & clean data   → Fix missing values, outliers
4. Feature engineering    → Transform raw data into useful signals
5. Choose & train model   → Pick algorithm, optimize
6. Evaluate               → Does it generalize to new data?
7. Deploy & monitor       → Real-world performance often differs

บทที่ 3: Neural Networks 101

Neuron: ตัวต่อชิ้นพื้นฐาน

neuron ตัวเดียวรับ input หลายค่า เอาแต่ละค่าไปคูณ weight แล้วรวมกัน บวก bias เข้าไป จากนั้นส่งผลลัพธ์ผ่าน activation function:

inputs:   x₁ = 0.5,  x₂ = 0.8,  x₃ = 0.3
weights:  w₁ = 0.4,  w₂ = -0.2, w₃ = 0.9
bias:     b  = 0.1

weighted sum = (0.5×0.4) + (0.8×-0.2) + (0.3×0.9) + 0.1
             = 0.2 - 0.16 + 0.27 + 0.1 = 0.41

output = activation(0.41) = sigmoid(0.41) ≈ 0.60
import numpy as np

def neuron(inputs, weights, bias, activation="relu"):
    z = np.dot(inputs, weights) + bias  # linear combination
    if activation == "relu":
        return max(0, z)                # ReLU: max(0, z)
    elif activation == "sigmoid":
        return 1 / (1 + np.exp(-z))    # sigmoid: 0 to 1
    elif activation == "tanh":
        return np.tanh(z)              # tanh: -1 to 1
    return z

จาก Neuron ตัวเดียว กลายเป็น Network

เอา neuron มาเรียงเป็น layer ซ้อนกัน → ได้ neural network:

Input Layer    Hidden Layer    Output Layer
[x₁]─────────→[n₁]─────────→[out]
[x₂]─────────→[n₂]
[x₃]─────────→[n₃]
               [n₄]

Each connection has a weight (learned during training)
Hidden layer finds intermediate features
Output layer gives the final prediction

Activation Function ที่ใช้บ่อย

Function สูตร ใช้ตรงไหน
ReLU max(0, x) Hidden layer (ตัวเลือก default)
Sigmoid 1/(1+e⁻ˣ) Output ของ binary classification
Softmax eˣᵢ / Σeˣ Output แบบ multi-class
GELU x·Φ(x) Transformer (LLM)
Tanh (eˣ-e⁻ˣ)/(eˣ+e⁻ˣ) RNN, hidden layer บางแบบ

Neural Network ตัวแรกของคุณ

import torch
import torch.nn as nn

# A simple 3-layer neural network
class SimpleNet(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super().__init__()
        self.layer1 = nn.Linear(input_size, hidden_size)
        self.relu = nn.ReLU()
        self.layer2 = nn.Linear(hidden_size, hidden_size)
        self.layer3 = nn.Linear(hidden_size, output_size)

    def forward(self, x):
        x = self.relu(self.layer1(x))  # input → hidden
        x = self.relu(self.layer2(x))  # hidden → hidden
        x = self.layer3(x)             # hidden → output
        return x

# Instantiate
model = SimpleNet(input_size=10, hidden_size=64, output_size=3)
print(model)
# Count parameters
total_params = sum(p.numel() for p in model.parameters())
print(f"Total parameters: {total_params:,}")  # 4,419

บทที่ 4: Deep Learning & Backpropagation

ทำไมถึงเรียกว่า "Deep"?

Deep learning = neural network ที่มี หลาย layer (deep หมายถึงมี hidden layer เยอะ) ยิ่ง layer เยอะ → ยิ่งเรียน pattern ที่ซับซ้อนได้

Shallow (1-2 layers): can classify simple shapes, basic text
Deep (10-100+ layers): can understand faces, language nuance, generate art

Neural Network เรียนรู้ยังไง: Backpropagation

การ train คือ loop ง่ายๆ แค่นี้:

1. FORWARD PASS:   Feed data through the network → get a prediction
2. COMPUTE LOSS:   How wrong was the prediction?
3. BACKWARD PASS:  Calculate how each weight contributed to the error
4. UPDATE WEIGHTS: Nudge each weight in the direction that reduces error
5. REPEAT:         Do this for millions of examples

Loss Function บอกว่า model ทายพลาดไปแค่ไหน:

# Mean Squared Error (regression)
def mse_loss(predictions, targets):
    return ((predictions - targets) ** 2).mean()

# Cross-Entropy (classification)
def cross_entropy_loss(logits, targets):
    return nn.CrossEntropyLoss()(logits, targets)

Gradient Descent คือวิธีอัปเดต weight:

new_weight = old_weight - learning_rate × gradient

learning_rate: how big a step to take (e.g., 0.001)
gradient: the slope — which direction reduces the error

Training Loop เต็มๆ ใน PyTorch

import torch
import torch.nn as nn
import torch.optim as optim

# Dummy data: 100 samples, 10 features, 3 classes
X = torch.randn(100, 10)
y = torch.randint(0, 3, (100,))

model = SimpleNet(10, 64, 3)
optimizer = optim.Adam(model.parameters(), lr=0.001)
criterion = nn.CrossEntropyLoss()

# Training loop
for epoch in range(50):
    # 1. Forward pass
    predictions = model(X)

    # 2. Compute loss
    loss = criterion(predictions, y)

    # 3. Backward pass (compute gradients)
    optimizer.zero_grad()   # clear old gradients
    loss.backward()         # compute new gradients

    # 4. Update weights
    optimizer.step()

    if epoch % 10 == 0:
        print(f"Epoch {epoch}: Loss = {loss.item():.4f}")

แนวคิดหลักของ Deep Learning

แนวคิด ความหมาย สำคัญยังไง
Epoch วิ่งผ่าน training data ครบหนึ่งรอบ epoch เยอะ = model เรียนได้มากขึ้น (แต่มีจุดอิ่มตัว)
Batch size ใช้กี่ sample ต่อการอัปเดต gradient หนึ่งครั้ง batch เล็ก = noise เยอะ แต่ได้อัปเดตถี่กว่า
Learning rate ระยะก้าวตอนอัปเดต weight ใหญ่ไป → diverge; เล็กไป → converge ช้า
Overfitting model จำ training data ได้หมด แต่เจอข้อมูลใหม่แล้วทายพลาด จับได้จาก validation loss; แก้ด้วย dropout หรือเพิ่มข้อมูล
Dropout สุ่มปิด neuron บางตัว (ให้ค่าเป็นศูนย์) ตอน train บังคับให้ model เรียน feature ที่ robust และลด overfitting
Batch Norm normalize input ของแต่ละ layer train ได้นิ่งขึ้น และใช้ learning rate สูงขึ้นได้

บทที่ 5: รู้จัก Large Language Model (LLM)

LLM คืออะไร?

Large Language Model คือ neural network (พูดให้ชัดคือ Transformer) ที่ train ด้วย text ปริมาณมหาศาล โดยมีงานเดียวคือทำนาย token ถัดไป ส่วนคำว่า "Large" หมายถึงมี parameter ระดับพันล้านตัว

Training: Learn from 15 trillion tokens of text (books, web, code...)
Task:     Given "The Eiffel Tower is in", predict "Paris"

After training: the model has compressed language patterns into
                billions of parameters → can generate coherent text

Text กลายเป็น Token ได้ยังไง

LLM ไม่ได้อ่านทีละตัวอักษรหรือทีละคำ แต่อ่านเป็น token คือ text ที่หั่นเป็นชิ้นๆ:

from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("gpt2")
text = "Generative AI is transforming the world!"
tokens = tokenizer.encode(text)
print(tokens)
# [8645, 876, 3068, 318, 28287, 262, 995, 0]
# 8 tokens for 40 characters (~5 chars/token on average)

LLM Generate ข้อความยังไง

ตอน inference LLM จะ generate ออกมาทีละ token:

Input: "The cat sat on"
Step 1: Predict → "the" (probability: 0.72) → append
Step 2: Predict → "mat" (probability: 0.65) → append
Step 3: Predict → "." (probability: 0.81) → append
Step 4: Predict → [END] → stop

Output: "The cat sat on the mat."

ตระกูล LLM หลักในปี 2026

ตระกูล ผู้สร้าง เหมาะกับ
GPT-4o OpenAI งานทั่วไป, multimodal
Claude 3.5/4 Anthropic reasoning, safety, long context
Gemini 2.0 Google multimodal, long context
LLaMA 3.1 Meta open source, self-hosting
Qwen 2.5 Alibaba หลายภาษา, ใช้ทรัพยากรคุ้ม
DeepSeek V3/R1 DeepSeek coding, คณิตศาสตร์, reasoning
Mistral Mistral AI ใช้ทรัพยากรคุ้ม, ค่ายจากยุโรป

บทที่ 6: Metric หลักสำหรับวัดผล Model

Loss

Loss บอกว่า model ทายพลาดไปแค่ไหน ยิ่งต่ำยิ่งดี

import torch
import torch.nn.functional as F

# Cross-entropy loss for a 3-class problem
logits = torch.tensor([[2.0, 1.0, 0.5]])  # model outputs (unnormalized)
target = torch.tensor([0])                 # correct class is 0

loss = F.cross_entropy(logits, target)
print(f"Loss: {loss.item():.4f}")  # lower is better

Accuracy

สัดส่วนที่ model ทายตรง ดูแล้วเข้าใจง่าย แต่หลอกตาได้ถ้าข้อมูลไม่สมดุล

def accuracy(predictions, targets):
    correct = (predictions.argmax(dim=1) == targets).sum().item()
    return correct / len(targets)

# Watch out: 99% accuracy sounds great...
# But if 99% of your data is "not fraud", a model that predicts
# "not fraud" for everything gets 99% accuracy with zero utility

Perplexity (สำหรับ Language Model)

Perplexity วัดว่า model "งง" แค่ไหนเวลาเจอ text จริง ยิ่งต่ำแปลว่า model ทาย text ได้แม่นกว่า

Perplexity = e^(average cross-entropy loss per token)

A perplexity of 10 means the model is as uncertain as if
it had to choose uniformly among 10 equally likely tokens.
A perplexity of 5 means it's doing better (fewer effective choices).

GPT-2:         perplexity ~35 on WikiText
GPT-3:         perplexity ~20
Modern LLMs:   perplexity ~8-15 (domain-dependent)
import torch
import torch.nn.functional as F
import math

def calculate_perplexity(model, tokenizer, text: str) -> float:
    inputs = tokenizer(text, return_tensors="pt")
    input_ids = inputs.input_ids

    with torch.no_grad():
        outputs = model(**inputs, labels=input_ids)
        loss = outputs.loss  # cross-entropy per token

    return math.exp(loss.item())

Metric สำคัญอื่นๆ

Metric ใช้กับ สูตร
Precision เมื่อ false positive สร้างความเสียหายสูง TP / (TP + FP)
Recall เมื่อ false negative สร้างความเสียหายสูง TP / (TP + FN)
F1 Score ถ่วง precision กับ recall ให้สมดุล 2 × (P × R) / (P + R)
BLEU คุณภาพการแปลภาษา N-gram ที่ตรงกับ reference
ROUGE คุณภาพการสรุปความ ส่วนที่ตรงกับ reference summary
BERTScore text สองชุดมีความหมายใกล้กันแค่ไหน Cosine similarity ของ BERT embedding

บทที่ 7: เซ็ตอัป Environment

ชุดเครื่องมือของ AI Developer

Python 3.11+        → Language (use pyenv or conda to manage versions)
PyTorch 2.x         → Deep learning framework (best for research + LLMs)
TensorFlow 2.x      → Alternative framework (strong in production/mobile)
Hugging Face        → Hub for models, datasets, tokenizers
Jupyter             → Interactive notebooks for exploration
CUDA / ROCm         → GPU acceleration (NVIDIA / AMD)

ทางเลือกที่ 1: ติดตั้งบนเครื่องตัวเอง

# Install Python 3.11 (using pyenv)
brew install pyenv   # macOS
pyenv install 3.11.9
pyenv global 3.11.9

# Create project environment
python -m venv genai-env
source genai-env/bin/activate  # Mac/Linux
# genai-env\Scripts\activate   # Windows

# Install core packages
pip install torch torchvision torchaudio   # PyTorch (CPU)
# For CUDA 12.1:
# pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121

pip install transformers          # Hugging Face Transformers
pip install datasets              # HF Datasets
pip install accelerate            # Multi-GPU / mixed precision
pip install diffusers             # Diffusion models
pip install sentence-transformers # Embeddings
pip install langchain             # LLM application framework
pip install openai anthropic      # API clients
pip install jupyter               # Notebooks
pip install numpy pandas matplotlib seaborn  # Data science essentials

# Verify GPU
python -c "import torch; print(torch.cuda.is_available(), torch.cuda.get_device_name(0))"

ทางเลือกที่ 2: Google Colab (GPU ฟรี เหมาะกับมือใหม่ที่สุด)

Google Colab ให้ใช้ GPU T4 ฟรี (VRAM 16 GB) พอสำหรับแบบฝึกหัดทุกข้อในซีรีส์นี้

# In a Colab notebook, most packages are pre-installed
# Check what GPU you have:
!nvidia-smi

# Install what's missing
!pip install -q transformers datasets accelerate

# Mount Google Drive to save model checkpoints
from google.colab import drive
drive.mount('/content/drive')

ทางเลือกที่ 3: cloud GPU service

Service Free Tier GPU เหมาะกับ
Google Colab มี (T4) T4 16GB ฝึกมือ, ทดลองเล็กๆ
Kaggle Notebooks มี (P100) P100 16GB งานแข่ง, dataset
Lightning AI มี T4 ทำ prototype เร็วๆ
RunPod ไม่มี ($0.20/hr) เลือกได้ทุกรุ่น ปรับ setup เองได้เต็มที่
Lambda Labs ไม่มี ($0.50/hr) A10, A100 train ระดับ production

Hugging Face Quickstart

อยากเริ่มใช้ AI model ให้เร็วที่สุด ใช้ pipeline ของ Hugging Face:

from transformers import pipeline

# Text generation
generator = pipeline("text-generation", model="gpt2")
result = generator("Generative AI is", max_new_tokens=50)
print(result[0]["generated_text"])

# Sentiment analysis
classifier = pipeline("sentiment-analysis")
result = classifier("This course is absolutely fantastic!")
print(result)  # [{'label': 'POSITIVE', 'score': 0.9998}]

# Text summarization
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
text = """Generative AI models have revolutionized how we interact with computers.
          These models can produce text, images, audio, and video that are
          increasingly indistinguishable from human-created content..."""
summary = summarizer(text, max_length=50, min_length=20)
print(summary[0]["summary_text"])

# Translation
translator = pipeline("translation_en_to_fr")
result = translator("Hello, I am learning Generative AI!")
print(result[0]["translation_text"])  # "Bonjour, j'apprends l'IA générative !"

เช็กว่า Environment พร้อมใช้

รัน script นี้ดูว่าทุกอย่างพร้อมแล้ว:

# health_check.py
import sys
print(f"Python: {sys.version}")

import torch
print(f"PyTorch: {torch.__version__}")
print(f"CUDA available: {torch.cuda.is_available()}")
if torch.cuda.is_available():
    print(f"GPU: {torch.cuda.get_device_name(0)}")
    print(f"VRAM: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB")

import transformers
print(f"Transformers: {transformers.__version__}")

from transformers import pipeline
pipe = pipeline("sentiment-analysis")
result = pipe("I love learning AI!")
print(f"Test inference: {result}")  # should print POSITIVE

print("\n✓ Environment ready for Generative AI!")

สรุป

พื้นฐานที่ทั้งซีรีส์ต้องใช้ ตอนนี้คุณมีครบแล้ว นี่คือสิ่งที่ต้องติดตัวไปตอนต่อๆ ไป:

แนวคิด สรุปสั้นๆ
AI vs. ML vs. DL AI คือเป้าหมาย; ML คือวิธีไปถึง; DL คือเครื่องยนต์ที่ขับ LLM
Generative AI สร้างของใหม่ทั้ง text, ภาพ, เสียง โดยอาศัยความน่าจะเป็น
Supervised vs. Unsupervised มี label ให้เรียน vs. หา pattern เองโดยไม่มี label
Neural network layer ที่เชื่อมกันด้วย weight และ weight ได้มาจากการเรียนข้อมูล
Backpropagation gradient ของ loss ไหลย้อนกลับ แล้วปรับ weight ทุก step
LLM Transformer ที่ train ให้ทำนาย token ถัดไปจาก text corpus ขนาดมหาศาล
Loss / Accuracy / Perplexity Loss คือสัญญาณที่ใช้ train; accuracy ใช้กับ classification; perplexity ใช้กับ language model
Environment ของคุณ PyTorch + Hugging Face + Colab = ชุดเครื่องมือขั้นต่ำที่พอเริ่มงานได้

ตอนต่อไปในซีรีส์ → Part 2: ทำงานกับ LLM — ลงมือจริงกับ tokenization, embedding, สถาปัตยกรรม Transformer, fine-tuning, RAG และสร้าง chatbot ตัวแรก

โจทย์ฝึกมือ

ก่อนไป Part 2 ลองทำโจทย์นี้ให้จบก่อน:

  1. เปิด notebook ใหม่ใน Google Colab
  2. รัน environment health check script ด้านบน
  3. ลอง pipeline("text-generation") กับ model สามตัวจาก HuggingFace Hub
  4. เทียบคุณภาพ output ดูว่า model ใหญ่กับเล็กให้ผลต่างกันแค่ไหน
  5. จับเวลา inference ด้วย time.time()

ทำโจทย์นี้ให้จบ เนื้อหาทั้ง part จะติดมือ แล้วค่อยต่อยอดชั้นถัดไป


มีคำถามหรืออยากคุยต่อ? ทักมาได้ทาง LinkedIn, X หรือส่ง email มาได้เลย

Discussion

Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.