Machine Learning (ML) เป็นสาขาของ AI ที่ให้คอมพิวเตอร์เรียนรู้จากข้อมูลเพื่อทำการทำนายหรือตัดสินใจโดยไม่ได้โปรแกรมโดยตรง Python เป็นภาษาหลักสำหรับ ML ด้วย Ecosystem ที่สมบูรณ์ที่สุด
การตั้งค่าสภาพแวดล้อม
# ติดตั้งไลบรารีหลัก pip install numpy scipy matplotlib scikit-learn pandas jupyter
ไลบรารีหลักและหน้าที่
| ไลบรารี | หน้าที่ |
|---|---|
| NumPy | Array Computing, Linear Algebra, Random Numbers |
| Pandas | Data Manipulation, CSV/Excel I/O, DataFrame |
| Matplotlib | Plotting, Visualization |
| Seaborn | Statistical Visualization (บน Matplotlib) |
| SciPy | Scientific Computing, Optimization, Stats |
| Scikit-learn | ML Algorithms: Classification, Regression, Clustering |
ขั้นตอนการทำ Machine Learning (ML Pipeline)
- Data Collection - รวบรวมข้อมูล
- Data Cleaning - จัดการ Missing Values, Outliers, Duplicates
- Exploratory Data Analysis (EDA) - สำรวจข้อมูลด้วย Visualization/Stats
- Feature Engineering - สร้าง/เลือก/แปลง Features
- Model Selection - เลือกอัลกอริทึมที่เหมาะสม
- Training - ฝึกโมเดลด้วย Training Data
- Evaluation - วัดประสิทธิภาพด้วย Test Data / Cross-Validation
- Deployment - นำไปใช้งานจริง
ตัวอย่างครบวงจร: Classification ด้วย Iris Dataset
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
# 1. Load Data
iris = load_iris()
X, y = iris.data, iris.target
feature_names = iris.feature_names
target_names = iris.target_names
# แปลงเป็น DataFrame เพื่อ EDA
df = pd.DataFrame(X, columns=feature_names)
df['target'] = y
df['species'] = df['target'].map({i: name for i, name in enumerate(target_names)})
# 2. EDA
print(df.head())
print(df.describe())
sns.pairplot(df, hue='species')
plt.show()
# 3. Train/Test Split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
# 4. Feature Scaling (สำคัญสำหรับ KNN, SVM, Neural Networks)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# 5. Model Training
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train_scaled, y_train)
# 6. Prediction & Evaluation
y_pred = knn.predict(X_test_scaled)
print(f"Accuracy: {accuracy_score(y_test, y_pred):.4f}")
print(classification_report(y_test, y_pred, target_names=target_names))
# Confusion Matrix
cm = confusion_matrix(y_test, y_pred)
sns.heatmap(cm, annot=True, fmt='d', xticklabels=target_names, yticklabels=target_names)
plt.xlabel('Predicted')
plt.ylabel('Actual')
plt.show()
ประเภทของ Machine Learning
| ประเภท | คำอธิบาย | ตัวอย่างอัลกอริทึม | Use Case |
|---|---|---|---|
| Supervised Learning | มี Label (Target) | Linear Regression, Decision Tree, Random Forest, SVM, KNN | การทำนายราคา, Spam Detection, Medical Diagnosis |
| Unsupervised Learning | ไม่มี Label | K-Means, Hierarchical Clustering, PCA, DBSCAN | Customer Segmentation, Anomaly Detection |
| Reinforcement Learning | เรียนรู้จาก Reward/Penalty | Q-Learning, DQN, PPO | Game AI, Robotics, Trading Bots |
Metrics สำคัญสำหรับ Classification
- Accuracy: สัดส่วนที่ทำนายถูกทั้งหมด
- Precision: ของที่ทำนาย Positive จริงๆ แล้ว Positive
- Recall: ของที่เป็น Positive จริงๆ ทำนายถูกกี่ตัว
- F1-Score: Harmonic Mean ของ Precision และ Recall
- ROC-AUC: ความสามารถแยกคลาสในเกณฑ์ต่างๆ
เคล็ดลับสำหรับผู้เริ่มต้น
- เริ่มจาก Scikit-learn ก่อน (API สม่ำเสมอ, เอกสารดี)
- ทำความเข้าใจ Train/Test Split และ Cross-Validation ให้ดี
- ไม่ควร Skip Feature Scaling สำหรับ Algorithms ที่คำนวณระยะทาง
- ลอง Baseline Model ง่ายๆ ก่อน (Dummy Classifier, Linear Regression)
- ใช้ Pipeline เพื่อป้องกัน Data Leakage
สรุป
Python + Scikit-learn ให้ Foundation ที่แข็งแกร่งสำหรับ Machine Learning การฝึกปฏิบัติจริงกับ Datasets หลากหลาย (Kaggle, UCI Repository) จะช่วยให้เข้าใจกลไกและ Best Practices ได้เร็วขึ้น