Technology

ai และ machine learning คือ

ai และ machine learning คอ
ai และ machine learning คือ | SiamCafe Blog
2025-11-13· อ. บอม — SiamCafe.net· 1,811 คำ

AI และ Machine Learning คืออะไร — คู่มือฉบับสมบูรณ์ 2026

AI (Artificial Intelligence) หรือปัญญาประดิษฐ์ คือศาสตร์ที่ทำให้คอมพิวเตอร์สามารถคิด เรียนรู้ และตัดสินใจได้คล้ายมนุษย์ Machine Learning (ML) เป็นสาขาย่อยของ AI ที่ใช้ข้อมูลและอัลกอริทึมในการเรียนรู้รูปแบบโดยไม่ต้อง program กฎเกณฑ์ทุกอย่างเอง Deep Learning เป็นส่วนย่อยของ ML ที่ใช้ neural networks หลายชั้นสำหรับงานซับซ้อน เช่น image recognition, NLP และ generative AI บทความนี้อธิบายพื้นฐาน AI/ML ครบถ้วน พร้อมตัวอย่าง Python code สำหรับเริ่มต้น

AI, ML, Deep Learning — ความแตกต่าง

# ai_ml_dl.py — AI vs ML vs Deep Learning
import json

class AIMLComparison:
    HIERARCHY = {
        "ai": {
            "name": "Artificial Intelligence (AI)",
            "definition": "ระบบที่แสดงพฤติกรรมอัจฉริยะ — คิด เรียนรู้ ตัดสินใจ",
            "scope": "กว้างที่สุด — ครอบคลุม ML, DL, expert systems, robotics",
            "examples": ["ChatGPT", "Self-driving cars", "Siri/Alexa", "AlphaGo"],
        },
        "ml": {
            "name": "Machine Learning (ML)",
            "definition": "ระบบที่เรียนรู้จากข้อมูล — หา patterns โดยไม่ต้อง hard-code rules",
            "scope": "สาขาย่อยของ AI — ใช้ algorithms เรียนรู้จาก data",
            "examples": ["Spam filter", "Recommendation systems", "Fraud detection", "Price prediction"],
        },
        "dl": {
            "name": "Deep Learning (DL)",
            "definition": "ML ที่ใช้ Neural Networks หลายชั้น — เลียนแบบสมองมนุษย์",
            "scope": "สาขาย่อยของ ML — เหมาะกับ unstructured data (image, text, audio)",
            "examples": ["Image recognition", "ChatGPT/LLM", "Voice synthesis", "Art generation"],
        },
    }

    ML_TYPES = {
        "supervised": {
            "name": "Supervised Learning (เรียนรู้แบบมีผู้สอน)",
            "description": "มี input + label (คำตอบ) — model เรียนรู้ mapping input → output",
            "algorithms": ["Linear Regression", "Logistic Regression", "Decision Tree", "Random Forest", "SVM", "Neural Networks"],
            "use_cases": "ทำนายราคาบ้าน, จำแนก spam/ham, วินิจฉัยโรค",
        },
        "unsupervised": {
            "name": "Unsupervised Learning (เรียนรู้แบบไม่มีผู้สอน)",
            "description": "มีแค่ input ไม่มี label — model หา patterns/clusters เอง",
            "algorithms": ["K-Means", "DBSCAN", "PCA", "Autoencoders"],
            "use_cases": "Customer segmentation, anomaly detection, dimensionality reduction",
        },
        "reinforcement": {
            "name": "Reinforcement Learning (เรียนรู้แบบเสริมแรง)",
            "description": "Agent เรียนรู้จาก reward/punishment — trial and error",
            "algorithms": ["Q-Learning", "DQN", "PPO", "A3C"],
            "use_cases": "เกม (AlphaGo), หุ่นยนต์, self-driving cars, trading bots",
        },
    }

    def show_hierarchy(self):
        print("=== AI > ML > Deep Learning ===\n")
        for key, item in self.HIERARCHY.items():
            print(f"[{item['name']}]")
            print(f"  {item['definition']}")
            print(f"  Examples: {', '.join(item['examples'][:3])}")
            print()

    def show_ml_types(self):
        print("=== ML Types ===")
        for key, ml in self.ML_TYPES.items():
            print(f"\n  [{ml['name']}]")
            print(f"    {ml['description']}")
            print(f"    Algorithms: {', '.join(ml['algorithms'][:4])}")
            print(f"    Use cases: {ml['use_cases']}")

comp = AIMLComparison()
comp.show_hierarchy()
comp.show_ml_types()

Python ML เบื้องต้น

# ml_basics.py — Basic ML with Python
import json

class MLBasics:
    CODE = """
# basic_ml.py — Machine Learning basics with scikit-learn
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report

# === 1. Load Data ===
# ตัวอย่าง: ทำนายว่าลูกค้าจะซื้อสินค้าหรือไม่
data = pd.DataFrame({
    'age': [25, 30, 35, 40, 45, 50, 55, 60, 22, 28, 33, 38, 42, 48, 52],
    'income': [30000, 45000, 55000, 65000, 75000, 85000, 90000, 70000, 25000, 40000, 50000, 60000, 70000, 80000, 95000],
    'visits': [2, 5, 3, 8, 10, 12, 6, 4, 1, 3, 7, 9, 11, 8, 15],
    'bought': [0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1],
})

# === 2. Prepare Data ===
X = data[['age', 'income', 'visits']]
y = data['bought']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Scale features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# === 3. Train Model ===
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train_scaled, y_train)

# === 4. Evaluate ===
y_pred = model.predict(X_test_scaled)
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.2f}")
print(classification_report(y_test, y_pred))

# === 5. Predict New Data ===
new_customer = scaler.transform([[35, 55000, 6]])
prediction = model.predict(new_customer)
probability = model.predict_proba(new_customer)
print(f"Will buy: {'Yes' if prediction[0] == 1 else 'No'}")
print(f"Probability: {probability[0][1]:.2f}")

# === 6. Feature Importance ===
importances = dict(zip(X.columns, model.feature_importances_))
for feat, imp in sorted(importances.items(), key=lambda x: -x[1]):
    print(f"  {feat}: {imp:.3f}")
"""

    def show_code(self):
        print("=== Basic ML Code ===")
        print(self.CODE[:600])

basics = MLBasics()
basics.show_code()

Deep Learning with PyTorch

# deep_learning.py — Deep Learning basics
import json

class DeepLearningBasics:
    CODE = """
# basic_dl.py — Simple Neural Network with PyTorch
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
import numpy as np

# === Define Neural Network ===
class SimpleNN(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super(SimpleNN, self).__init__()
        self.layer1 = nn.Linear(input_size, hidden_size)
        self.relu = nn.ReLU()
        self.dropout = nn.Dropout(0.2)
        self.layer2 = nn.Linear(hidden_size, hidden_size // 2)
        self.layer3 = nn.Linear(hidden_size // 2, output_size)
        self.sigmoid = nn.Sigmoid()
    
    def forward(self, x):
        x = self.relu(self.layer1(x))
        x = self.dropout(x)
        x = self.relu(self.layer2(x))
        x = self.sigmoid(self.layer3(x))
        return x

# === Training ===
def train_model(model, train_loader, epochs=100, lr=0.001):
    criterion = nn.BCELoss()
    optimizer = optim.Adam(model.parameters(), lr=lr)
    
    for epoch in range(epochs):
        total_loss = 0
        for X_batch, y_batch in train_loader:
            optimizer.zero_grad()
            outputs = model(X_batch)
            loss = criterion(outputs.squeeze(), y_batch.float())
            loss.backward()
            optimizer.step()
            total_loss += loss.item()
        
        if (epoch + 1) % 20 == 0:
            print(f"Epoch {epoch+1}/{epochs}, Loss: {total_loss/len(train_loader):.4f}")

# === Usage ===
# X_tensor = torch.FloatTensor(X_train_scaled)
# y_tensor = torch.FloatTensor(y_train.values)
# dataset = TensorDataset(X_tensor, y_tensor)
# loader = DataLoader(dataset, batch_size=8, shuffle=True)
# model = SimpleNN(input_size=3, hidden_size=32, output_size=1)
# train_model(model, loader, epochs=100)
"""

    def show_code(self):
        print("=== Deep Learning Code ===")
        print(self.CODE[:600])

dl = DeepLearningBasics()
dl.show_code()

AI/ML Applications ในชีวิตจริง

# applications.py — Real-world AI/ML applications
import json

class AIApplications:
    APPS = {
        "chatgpt": {
            "name": "ChatGPT / LLMs",
            "type": "Generative AI (NLP)",
            "description": "AI ที่สนทนา ตอบคำถาม เขียนโค้ด แปลภาษา สรุปข้อมูล",
            "tech": "Transformer architecture, GPT-4, fine-tuning, RLHF",
        },
        "image_recognition": {
            "name": "Image Recognition",
            "type": "Computer Vision (Deep Learning)",
            "description": "จดจำใบหน้า ตรวจจับวัตถุ วินิจฉัยโรคจากภาพ X-ray",
            "tech": "CNN (Convolutional Neural Network), YOLO, ResNet",
        },
        "recommendation": {
            "name": "Recommendation Systems",
            "type": "ML (Collaborative/Content Filtering)",
            "description": "แนะนำสินค้า (Shopee), หนัง (Netflix), เพลง (Spotify)",
            "tech": "Collaborative filtering, matrix factorization, deep learning",
        },
        "self_driving": {
            "name": "Self-Driving Cars",
            "type": "AI (CV + RL + Sensor Fusion)",
            "description": "รถขับเองอัตโนมัติ — Tesla Autopilot, Waymo",
            "tech": "Computer vision, LiDAR, reinforcement learning, sensor fusion",
        },
        "fraud_detection": {
            "name": "Fraud Detection",
            "type": "ML (Anomaly Detection)",
            "description": "ตรวจจับธุรกรรมฉ้อโกง — banking, credit card, insurance",
            "tech": "Random Forest, XGBoost, autoencoders, real-time streaming",
        },
        "healthcare": {
            "name": "Healthcare AI",
            "type": "Deep Learning (Medical Imaging)",
            "description": "วินิจฉัยโรคจากภาพ CT/MRI, ค้นหายาใหม่, predict patient outcomes",
            "tech": "CNN, transformer, federated learning, drug discovery models",
        },
    }

    def show_apps(self):
        print("=== AI/ML Applications ===\n")
        for key, app in self.APPS.items():
            print(f"[{app['name']}] ({app['type']})")
            print(f"  {app['description']}")
            print(f"  Tech: {app['tech']}")
            print()

    def thai_examples(self):
        print("=== AI ในไทย ===")
        examples = [
            "SCB — AI fraud detection ตรวจจับธุรกรรมผิดปกติ",
            "BDMS — AI วินิจฉัยโรคจากภาพ X-ray",
            "LINE MAN — AI recommendation + dynamic pricing",
            "Shopee Thailand — AI product recommendation + search",
            "BOT — AI วิเคราะห์เศรษฐกิจ + NLP อ่านข่าว",
        ]
        for ex in examples:
            print(f"  • {ex}")

apps = AIApplications()
apps.show_apps()
apps.thai_examples()

เริ่มต้นเรียน AI/ML

# learning_path.py — AI/ML learning path
import json

class LearningPath:
    PATH = {
        "beginner": {
            "name": "Level 1: พื้นฐาน (1-3 เดือน)",
            "skills": ["Python programming", "NumPy, Pandas", "Statistics พื้นฐาน", "Data visualization (Matplotlib)"],
            "resources": ["Codecademy Python", "Khan Academy Statistics", "Kaggle Learn"],
        },
        "intermediate": {
            "name": "Level 2: ML Fundamentals (3-6 เดือน)",
            "skills": ["scikit-learn", "Supervised/Unsupervised learning", "Model evaluation", "Feature engineering"],
            "resources": ["Andrew Ng ML Course (Coursera)", "Hands-On ML Book", "Kaggle Competitions"],
        },
        "advanced": {
            "name": "Level 3: Deep Learning (6-12 เดือน)",
            "skills": ["PyTorch/TensorFlow", "CNN, RNN, Transformer", "NLP, Computer Vision", "MLOps basics"],
            "resources": ["fast.ai", "Deep Learning Specialization (Coursera)", "Papers with Code"],
        },
        "expert": {
            "name": "Level 4: Specialization (12+ เดือน)",
            "skills": ["Research papers", "Custom architectures", "LLMs/GenAI", "Production ML systems"],
            "resources": ["arXiv papers", "Open-source contributions", "Industry projects"],
        },
    }

    TOOLS = {
        "python": "Python — ภาษาหลักสำหรับ AI/ML",
        "jupyter": "Jupyter Notebook — interactive coding + visualization",
        "sklearn": "scikit-learn — ML library ง่ายที่สุด",
        "pytorch": "PyTorch — Deep Learning framework (research + production)",
        "tensorflow": "TensorFlow/Keras — Deep Learning framework (production)",
        "huggingface": "Hugging Face — pre-trained models + NLP",
        "kaggle": "Kaggle — datasets + competitions + learning",
    }

    def show_path(self):
        print("=== Learning Path ===\n")
        for key, level in self.PATH.items():
            print(f"[{level['name']}]")
            print(f"  Skills: {', '.join(level['skills'][:3])}")
            print(f"  Resources: {', '.join(level['resources'][:2])}")
            print()

    def show_tools(self):
        print("=== Essential Tools ===")
        for key, desc in self.TOOLS.items():
            print(f"  [{key}] {desc}")

path = LearningPath()
path.show_path()
path.show_tools()

FAQ - คำถามที่พบบ่อย

Q: AI กับ ML ต่างกันอย่างไร?

A: AI = แนวคิดกว้างๆ ที่ทำให้เครื่องจักรฉลาด (รวม rule-based systems, robotics, ML) ML = วิธีการหนึ่งของ AI ที่ใช้ข้อมูลเรียนรู้รูปแบบ (ไม่ต้อง hard-code rules) เปรียบเทียบ: AI = แพทย์ (ครอบคลุมทุกสาขา), ML = ศัลยแพทย์ (เชี่ยวชาญเฉพาะทาง) ทุก ML เป็น AI แต่ไม่ใช่ทุก AI เป็น ML

Q: ต้องเก่งคณิตศาสตร์ไหมถึงจะทำ ML ได้?

A: ขึ้นกับระดับ: ใช้ ML (apply): ไม่ต้องเก่งมาก — scikit-learn, Hugging Face ใช้งานได้เลย เข้าใจ ML: ต้องรู้ Linear Algebra, Calculus, Probability/Statistics พื้นฐาน Research ML: ต้องเก่งคณิตศาสตร์มาก แนะนำ: เริ่มจากการใช้งาน → เรียนคณิตศาสตร์ตามที่ต้องการเข้าใจ

Q: Python กับ R อันไหนดีสำหรับ ML?

A: Python: แนะนำ — ecosystem ใหญ่กว่า (PyTorch, TensorFlow, Hugging Face), ใช้ได้ทั้ง ML + web dev + production R: ดีสำหรับ statistical analysis + data visualization เฉพาะทาง ปัจจุบัน: Python เป็น standard สำหรับ ML/AI — ถ้าเลือกได้อันเดียว เลือก Python

Q: Generative AI (ChatGPT) ทำงานอย่างไร?

A: ใช้ Transformer architecture: เรียนรู้จากข้อความจำนวนมหาศาล (internet) ทำนายคำถัดไป (next token prediction) — ฝึกด้วย self-supervised learning จากนั้น fine-tune ด้วย RLHF (Reinforcement Learning from Human Feedback) ผลลัพธ์: generate text ที่มีความหมาย เข้าใจ context สนทนาได้ ข้อจำกัด: hallucination (ตอบผิดอย่างมั่นใจ), knowledge cutoff, ไม่มี reasoning จริง

📖 บทความที่เกี่ยวข้อง

machine learning supervised unsupervised คืออ่านบทความ → GraphQL Subscriptions Machine Learning Pipelineอ่านบทความ → Server-Sent Events Machine Learning Pipelineอ่านบทความ → Htmx Alpine.js Machine Learning Pipelineอ่านบทความ → Shadcn UI Machine Learning Pipelineอ่านบทความ →

📚 ดูบทความทั้งหมด →