AI Machine Learning Deep Learning
AI เป็นสาขาที่กว้างที่สุด ครอบคลุมทุกอย่างที่ทำให้คอมพิวเตอร์ฉลาด Machine Learning เป็น Subset ของ AI ที่เรียนรู้จากข้อมูล Deep Learning เป็น Subset ของ ML ที่ใช้ Neural Networks หลายชั้น
| หัวข้อ | AI | Machine Learning | Deep Learning |
|---|---|---|---|
| ขอบเขต | กว้างที่สุด | Subset ของ AI | Subset ของ ML |
| วิธีการ | Rule-based + Learning | เรียนจากข้อมูล | Neural Networks |
| ข้อมูล | น้อยถึงมาก | ปานกลาง | มากที่สุด |
| Feature Engineering | Manual | Manual + Auto | อัตโนมัติ |
| ตัวอย่าง | Expert Systems, Chatbot | Recommendation, Spam Filter | Image Recognition, GPT |
Machine Learning ด้วย Python
# ml_basics.py — Machine Learning พื้นฐานด้วย Scikit-learn
# pip install scikit-learn pandas numpy matplotlib
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
# === 1. สร้างข้อมูลตัวอย่าง ===
np.random.seed(42)
n_samples = 1000
data = pd.DataFrame({
"age": np.random.randint(18, 70, n_samples),
"income": np.random.randint(15000, 150000, n_samples),
"credit_score": np.random.randint(300, 850, n_samples),
"loan_amount": np.random.randint(10000, 500000, n_samples),
"employment_years": np.random.randint(0, 30, n_samples),
})
# Label: จะผิดนัดชำระหรือไม่
data["default"] = ((data["credit_score"] < 500) &
(data["loan_amount"] > data["income"] * 3)).astype(int)
print(f"Dataset: {data.shape}")
print(f"Default rate: {data['default'].mean():.1%}")
# === 2. เตรียมข้อมูล ===
X = data.drop("default", axis=1)
y = data["default"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# === 3. เปรียบเทียบ Models ===
models = {
"Logistic Regression": LogisticRegression(max_iter=1000),
"Decision Tree": DecisionTreeClassifier(max_depth=5),
"Random Forest": RandomForestClassifier(n_estimators=100),
"Gradient Boosting": GradientBoostingClassifier(n_estimators=100),
"SVM": SVC(kernel="rbf"),
"KNN": KNeighborsClassifier(n_neighbors=5),
}
print(f"\nModel Comparison:")
print(f"{'Model':<25} {'Accuracy':>10} {'CV Mean':>10}")
print(f"{'─'*45}")
best_model = None
best_score = 0
for name, model in models.items():
model.fit(X_train_scaled, y_train)
y_pred = model.predict(X_test_scaled)
acc = accuracy_score(y_test, y_pred)
cv_scores = cross_val_score(model, X_train_scaled, y_train, cv=5)
cv_mean = cv_scores.mean()
print(f" {name:<25} {acc:>9.3f} {cv_mean:>9.3f}")
if cv_mean > best_score:
best_score = cv_mean
best_model = name
print(f"\nBest Model: {best_model} (CV: {best_score:.3f})")
Deep Learning ด้วย PyTorch
# deep_learning.py — Deep Learning ด้วย PyTorch
# pip install torch torchvision
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
import numpy as np
# === 1. Neural Network Model ===
class SimpleNN(nn.Module):
"""Neural Network สำหรับ Classification"""
def __init__(self, input_size, hidden_sizes, output_size, dropout=0.3):
super().__init__()
layers = []
prev_size = input_size
for hidden_size in hidden_sizes:
layers.extend([
nn.Linear(prev_size, hidden_size),
nn.BatchNorm1d(hidden_size),
nn.ReLU(),
nn.Dropout(dropout),
])
prev_size = hidden_size
layers.append(nn.Linear(prev_size, output_size))
self.network = nn.Sequential(*layers)
def forward(self, x):
return self.network(x)
# === 2. Training Loop ===
class Trainer:
def __init__(self, model, lr=0.001):
self.model = model
self.criterion = nn.CrossEntropyLoss()
self.optimizer = optim.Adam(model.parameters(), lr=lr)
self.history = {"train_loss": [], "val_loss": [], "val_acc": []}
def train_epoch(self, dataloader):
self.model.train()
total_loss = 0
for X_batch, y_batch in dataloader:
self.optimizer.zero_grad()
outputs = self.model(X_batch)
loss = self.criterion(outputs, y_batch)
loss.backward()
self.optimizer.step()
total_loss += loss.item()
return total_loss / len(dataloader)
def evaluate(self, dataloader):
self.model.eval()
total_loss = 0
correct = 0
total = 0
with torch.no_grad():
for X_batch, y_batch in dataloader:
outputs = self.model(X_batch)
loss = self.criterion(outputs, y_batch)
total_loss += loss.item()
_, predicted = torch.max(outputs, 1)
total += y_batch.size(0)
correct += (predicted == y_batch).sum().item()
return total_loss / len(dataloader), correct / total
def fit(self, train_loader, val_loader, epochs=50):
for epoch in range(epochs):
train_loss = self.train_epoch(train_loader)
val_loss, val_acc = self.evaluate(val_loader)
self.history["train_loss"].append(train_loss)
self.history["val_loss"].append(val_loss)
self.history["val_acc"].append(val_acc)
if (epoch + 1) % 10 == 0:
print(f" Epoch {epoch+1}/{epochs} — "
f"Train Loss: {train_loss:.4f} | "
f"Val Loss: {val_loss:.4f} | "
f"Val Acc: {val_acc:.3f}")
# === 3. ตัวอย่างการใช้งาน ===
# สร้างข้อมูลจำลอง
np.random.seed(42)
X = np.random.randn(2000, 10).astype(np.float32)
y = (X[:, 0] + X[:, 1] > 0).astype(np.int64)
# แบ่งข้อมูล
split = int(0.8 * len(X))
X_train = torch.tensor(X[:split])
y_train = torch.tensor(y[:split])
X_val = torch.tensor(X[split:])
y_val = torch.tensor(y[split:])
train_ds = TensorDataset(X_train, y_train)
val_ds = TensorDataset(X_val, y_val)
train_loader = DataLoader(train_ds, batch_size=64, shuffle=True)
val_loader = DataLoader(val_ds, batch_size=64)
# สร้าง Model
model = SimpleNN(
input_size=10,
hidden_sizes=[64, 32, 16],
output_size=2,
dropout=0.2,
)
print(f"Model Parameters: {sum(p.numel() for p in model.parameters()):,}")
# Train
trainer = Trainer(model, lr=0.001)
trainer.fit(train_loader, val_loader, epochs=50)
AI Use Cases และ Tools
# ai_tools.py — AI Tools และ Use Cases
ai_landscape = {
"Natural Language Processing (NLP)": {
"tasks": ["Text Classification", "Sentiment Analysis",
"Named Entity Recognition", "Machine Translation",
"Question Answering", "Text Generation"],
"tools": ["Hugging Face Transformers", "spaCy", "NLTK", "OpenAI API"],
"models": ["GPT-4", "BERT", "LLaMA", "T5"],
},
"Computer Vision": {
"tasks": ["Image Classification", "Object Detection",
"Semantic Segmentation", "Face Recognition",
"OCR", "Image Generation"],
"tools": ["OpenCV", "TorchVision", "YOLO", "Detectron2"],
"models": ["ResNet", "YOLO v8", "ViT", "Stable Diffusion"],
},
"Recommendation Systems": {
"tasks": ["Product Recommendations", "Content Recommendations",
"Collaborative Filtering", "Content-based Filtering"],
"tools": ["Surprise", "LightFM", "TensorFlow Recommenders"],
"models": ["Matrix Factorization", "Neural CF", "Two-Tower"],
},
"Time Series": {
"tasks": ["Forecasting", "Anomaly Detection",
"Trend Analysis", "Seasonal Decomposition"],
"tools": ["Prophet", "statsmodels", "Darts", "NeuralProphet"],
"models": ["ARIMA", "LSTM", "Transformer", "N-BEATS"],
},
}
# Learning Path
learning_path = [
("Month 1-2", "Python + Math", [
"Python Programming (Variables, Functions, OOP)",
"NumPy, Pandas, Matplotlib",
"Linear Algebra (Vectors, Matrices)",
"Statistics (Mean, Variance, Distributions)",
]),
("Month 3-4", "Machine Learning", [
"Scikit-learn (Classification, Regression)",
"Feature Engineering",
"Model Evaluation (CV, Metrics)",
"Kaggle Competitions",
]),
("Month 5-6", "Deep Learning", [
"PyTorch / TensorFlow",
"CNN (Image Classification)",
"RNN / LSTM (Sequence)",
"Transfer Learning",
]),
("Month 7-8", "Specialization", [
"NLP + Transformers",
"Computer Vision",
"Reinforcement Learning",
"MLOps (Deployment)",
]),
]
print("AI Landscape:")
for domain, info in ai_landscape.items():
print(f"\n [{domain}]")
print(f" Tasks: {', '.join(info['tasks'][:3])}")
print(f" Tools: {', '.join(info['tools'][:3])}")
print(f" Models: {', '.join(info['models'][:3])}")
print(f"\n{'='*55}")
print("AI Learning Path:")
for period, topic, items in learning_path:
print(f"\n {period}: {topic}")
for item in items:
print(f" [ ] {item}")
เคล็ดลับ
- เริ่มจาก ML: เรียน Machine Learning ก่อน Deep Learning เข้าใจพื้นฐานให้แน่น
- ฝึกกับข้อมูลจริง: ใช้ Kaggle Datasets ฝึกกับข้อมูลจริง ไม่ใช่แค่ Toy Examples
- เข้าใจ Math: Linear Algebra, Statistics สำคัญมาก อย่าข้าม
- PyTorch vs TensorFlow: เลือกอันใดอันหนึ่ง PyTorch นิยมในงานวิจัย TensorFlow นิยมใน Production
- Transfer Learning: ใช้ Pre-trained Models แทนเทรนจากศูนย์ ประหยัดเวลาและ GPU
- อ่าน Papers: อ่าน Papers จาก arXiv ติดตาม State-of-the-Art
AI คืออะไร
ปัญญาประดิษฐ์ สาขา Computer Science ทำให้คอมพิวเตอร์คิดตัดสินใจเหมือนมนุษย์ ครอบคลุม ML DL NLP Computer Vision Robotics สร้างระบบเรียนรู้ปรับตัวได้เอง
Machine Learning ต่างจาก AI อย่างไร
ML เป็น Subset ของ AI เรียนรู้จากข้อมูลไม่ต้องเขียนกฎ มี Supervised Unsupervised Reinforcement Learning AI กว้างกว่ารวม Rule-based Systems ด้วย
Deep Learning คืออะไร
Subset ของ ML ใช้ Neural Networks หลายชั้น เรียนรู้ Features จากข้อมูลเอง ไม่ต้อง Feature Engineering เหมาะข้อมูลมาก รูปภาพเสียงข้อความ CNN Image RNN Transformer Text
เริ่มต้นเรียน AI ต้องรู้อะไรบ้าง
Python Programming คณิตศาสตร์ Linear Algebra Statistics Calculus Data Processing Pandas NumPy ML Scikit-learn DL TensorFlow PyTorch ฝึกกับ Kaggle อ่าน Research Papers
สรุป
AI ครอบคลุมกว้างที่สุด ML เรียนจากข้อมูล DL ใช้ Neural Networks เริ่มจาก Python Math แล้วเรียน ML ด้วย Scikit-learn ต่อด้วย DL ด้วย PyTorch ฝึกกับข้อมูลจริงบน Kaggle ใช้ Transfer Learning ประหยัดเวลา ติดตาม State-of-the-Art จาก Papers
