Nếu bạn hỏi một người bình thường: "Machine Learning là gì?", câu trả lời thường là "AI thông minh, tự học mọi thứ". Nhưng thực tế, Machine Learning không phải phép màu - nó là toán học được áp dụng vào dữ liệu để tìm ra patterns (mẫu).
Hãy tưởng tượng bạn dạy trẻ con nhận biết chó và mèo. Bạn không viết rules kiểu "nếu có 4 chân + đuôi dài + kêu gâu gâu = chó". Thay vào đó, bạn cho trẻ xem hàng trăm ảnh chó và mèo, và não bộ trẻ tự học pattern để phân biệt.
Machine Learning hoạt động y chang vậy. Thay vì lập trình viên viết rules, ta cho máy tính học từ examples.
Bạn cung cấp cho máy tính cả input và output mong muốn. Máy học cách map từ input → output.
Ví dụ thực tế:
Hai loại bài toán:
Classification (Phân loại): Output là category rời rạc
Regression (Hồi quy): Output là số liên tục
Workflow điển hình:
1. Thu thập data có label: (email, spam/not spam)
2. Chia data: 80% training, 20% testing
3. Train model trên training data
4. Đánh giá model trên testing data
5. Deploy model để predict data mới
Bạn chỉ cho máy input, không có label. Máy tự tìm ra structure ẩn trong data.
Clustering (Phân cụm):
Ví dụ K-Means Clustering:
Input: Thông tin khách hàng (tuổi, thu nhập, tần suất mua hàng)
Output: 3 clusters
- Cluster 1: "Young professionals" (trẻ, thu nhập cao, mua thường xuyên)
- Cluster 2: "Bargain hunters" (mọi lứa tuổi, nhạy cảm giá)
- Cluster 3: "Occasional buyers" (mua ít, chi tiêu trung bình)
Dimensionality Reduction (Giảm chiều):
Anomaly Detection:
Thực tế, label data rất đắt (cần con người label từng sample). Semi-supervised sử dụng một ít labeled data + nhiều unlabeled data.
Ví dụ:
Agent (tác nhân) học cách hành động trong environment để maximize reward (phần thưởng).
Ví dụ:
Workflow:
1. Agent quan sát state hiện tại (vị trí xe, tốc độ, vật cản...)
2. Agent chọn action (tăng tốc, phanh, rẽ trái...)
3. Environment cho reward và state mới
4. Agent update policy để chọn action tốt hơn lần sau
Đây là concept quan trọng nhất để hiểu tại sao model của bạn không hoạt động tốt.
Bias (độ chệch): Model quá đơn giản, không thể capture pattern phức tạp trong data.
Ví dụ:
Actual pattern: ___/‾‾‾\___ (curved)
Model: ____________ (straight line)
Dấu hiệu:
Variance (độ phân tán): Model quá phức tạp, học cả noise trong training data thay vì chỉ học pattern thực.
Ví dụ:
Training data: • • •●• ••
Model curve: ︵︶︵︶︵︶︵ (quá khớp từng điểm, kể cả noise)
Test data: FAIL (model không generalize)
Dấu hiệu:
Đây là mâu thuẫn không thể tránh khỏi:
Simple Model (Linear) Complex Model (Deep NN)
High Bias ←────────────────→ High Variance
Underfit Overfit
Sweet spot: Model vừa đủ phức tạp để capture pattern, nhưng không quá phức tạp để học noise.
Trong thực tế:
Model Bias Variance Best for
-------------------------------------------------
Linear Reg High Low Simple linear patterns
Decision Tree Low High Non-linear but needs pruning
Random Forest Medium Medium General purpose (good balance)
Deep NN Low Very High Complex patterns + large data
Nguyên nhân:
Giải pháp:
✅ Tăng complexity: Thêm layers (neural network), tăng depth (decision tree)
✅ Thêm features: Feature engineering để tạo features mới
✅ Train lâu hơn: Tăng số epochs
✅ Giảm regularization: Bỏ hoặc giảm penalty
Nguyên nhân:
Giải pháp:
1. Regularization (L1/L2):
Thêm penalty vào loss function để model không được phép có weights quá lớn.
# L2 Regularization (Ridge)
Loss = MSE + λ * Σ(weights²)
# L1 Regularization (Lasso)
Loss = MSE + λ * Σ|weights|
2. Dropout (Neural Networks):
Trong mỗi training iteration, randomly tắt một số neurons (VD: 50%).
# Dropout layer
x = Dense(128)(x)
x = Dropout(0.5)(x) # Randomly disable 50% neurons
→ Buộc network không phụ thuộc quá nhiều vào một vài neurons cụ thể.
3. Early Stopping:
Monitor validation error trong quá trình training. Stop khi validation error bắt đầu tăng (sign of overfitting).
Epoch 1: train_loss=0.5, val_loss=0.6
Epoch 2: train_loss=0.3, val_loss=0.4
Epoch 3: train_loss=0.2, val_loss=0.35 ← best
Epoch 4: train_loss=0.1, val_loss=0.38 ← val_loss tăng, STOP!
4. Data Augmentation:
Tăng lượng training data bằng cách tạo variants.
Ví dụ với ảnh:
→ Model học được nhiều variations, generalize tốt hơn.
5. Cross-Validation:
Thay vì chia data 1 lần (80/20), chia thành k folds và train k lần.
Fold 1: [Test] [Train] [Train] [Train] [Train]
Fold 2: [Train] [Test] [Train] [Train] [Train]
Fold 3: [Train] [Train] [Test] [Train] [Train]
...
Average kết quả từ k lần → đánh giá chính xác hơn.
Mục tiêu: Tìm đường thẳng y = wx + b fit tốt nhất với data.
Ví dụ: Dự đoán giá nhà dựa trên diện tích
Giá = 50 * Diện_tích + 200Cách học:
MSE = (1/n) * Σ(y_actual - y_predicted)²Ưu điểm: Đơn giản, nhanh, interpretable
Nhược điểm: Chỉ fit được linear patterns
Mặc dù tên có "Regression" nhưng đây là classification algorithm.
Mục tiêu: Dự đoán xác suất một sample thuộc class nào.
Ví dụ: Dự đoán khách hàng có churn (rời bỏ) không
Công thức:
z = wx + b
P(y=1) = sigmoid(z) = 1 / (1 + e^(-z))
Sigmoid function "squash" output vào khoảng [0, 1] → interpret như probability.
Ưu điểm: Cho probability thay vì hard prediction, nhanh
Nhược điểm: Chỉ fit được linear decision boundary
Model học một cây quyết định dựa trên các câu hỏi về features.
Ví dụ: Loan Approval
[Income > $50k?]
/ \
Yes No
/ \
[Credit Score > 700?] [Reject]
/ \
Yes No
/ \
[Approve] [Debt Ratio > 0.4?]
/ \
Yes No
/ \
[Reject] [Approve]
Cách tree "học":
Ưu điểm:
Nhược điểm:
Solution: Random Forest = ensemble của nhiều decision trees
Mục tiêu: Tìm hyperplane phân chia 2 classes sao cho margin (khoảng cách đến điểm gần nhất) là lớn nhất.
Class A: ○ ○ ○ | ● ● ● :Class B
○ | ●
○ | ●
|
← margin →
Đường phân chia giữa có margin lớn nhất → generalize tốt nhất.
Kernel Trick: Data không linearly separable trong không gian ban đầu? Map lên không gian cao hơn!
2D space (không phân chia được): ○●○●○●
●○●○●○
3D space (sau kernel): ○○○○○○ (trên)
------ (hyperplane)
●●●●●● (dưới)
Ưu điểm: Rất mạnh cho high-dimensional data, effective với small datasets
Nhược điểm: Chậm với large datasets, khó tune hyperparameters
"Tôi muốn giải quyết vấn đề gì?"
❌ Mơ hồ: "Tăng doanh thu"
✅ Cụ thể: "Dự đoán khách hàng có khả năng churn để marketing team can thiệp sớm"
Xác định:
Thu thập data:
Exploratory Data Analysis (EDA):
# Understand data
df.info() # Data types, missing values
df.describe() # Statistics (mean, std, min, max)
df['column'].value_counts() # Distribution
# Visualize
import matplotlib.pyplot as plt
df.hist(bins=50, figsize=(20,15))
plt.show()
# Correlation
correlation_matrix = df.corr()
sns.heatmap(correlation_matrix, annot=True)
Phát hiện:
Xử lý missing values:
# Option 1: Drop rows có missing
df.dropna()
# Option 2: Impute với mean/median/mode
df['age'].fillna(df['age'].median(), inplace=True)
# Option 3: Impute với model prediction
Feature Scaling:
Nhiều algorithms (SVM, neural networks, k-NN) nhạy cảm với scale của features.
# Normalization (scale về [0, 1])
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
df_normalized = scaler.fit_transform(df)
# Standardization (mean=0, std=1)
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
df_standardized = scaler.fit_transform(df)
Khi nào dùng gì?
Feature Encoding:
ML models chỉ hiểu numbers, không hiểu text.
# One-Hot Encoding (cho categorical features không có order)
# Input: ['Red', 'Blue', 'Red', 'Green']
# Output: Red Blue Green
# 1 0 0
# 0 1 0
# 1 0 0
# 0 0 1
pd.get_dummies(df['color'])
# Label Encoding (cho categorical có order)
# Input: ['Low', 'High', 'Medium', 'Low']
# Output: [0, 2, 1, 0] # Low=0, Medium=1, High=2
from sklearn.preprocessing import LabelEncoder
encoder = LabelEncoder()
df['priority_encoded'] = encoder.fit_transform(df['priority'])
Đây là "nghệ thuật" tạo features mới từ features có sẵn để improve model performance.
Ví dụ với real estate:
# Raw features: area (m²), price (VNĐ)
df['price_per_sqm'] = df['price'] / df['area']
# Raw features: year_built
df['building_age'] = 2024 - df['year_built']
# Interaction features
df['location_x_area'] = df['location_score'] * df['area']
Domain knowledge rất quan trọng ở bước này!
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X, y,
test_size=0.2, # 80% train, 20% test
random_state=42, # Reproducibility
stratify=y # Giữ tỷ lệ classes giống nhau
)
Rule: KHÔNG BAO GIỜ sử dụng test set trong quá trình training hay tuning!
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
# Try multiple models
models = {
'Logistic': LogisticRegression(),
'Decision Tree': DecisionTreeClassifier(),
'Random Forest': RandomForestClassifier()
}
for name, model in models.items():
model.fit(X_train, y_train)
score = model.score(X_test, y_test)
print(f"{name}: {score:.4f}")
Accuracy không phải lúc nào cũng là metric tốt!
Ví dụ: Fraud detection
→ Cần metrics khác: Precision, Recall, F1-Score (sẽ đề cập kỹ trong bài tiếp).
Mỗi model có hyperparameters cần tune (learning rate, max depth, số trees...).
from sklearn.model_selection import GridSearchCV
param_grid = {
'max_depth': [3, 5, 7, 10],
'n_estimators': [50, 100, 200],
'min_samples_split': [2, 5, 10]
}
grid_search = GridSearchCV(
RandomForestClassifier(),
param_grid,
cv=5, # 5-fold cross-validation
scoring='f1'
)
grid_search.fit(X_train, y_train)
best_model = grid_search.best_estimator_
Model trained xong, giờ phải đưa vào production!
# Save model
import joblib
joblib.dump(model, 'model.pkl')
# Load và predict
model = joblib.load('model.pkl')
prediction = model.predict(new_data)
Wrap model trong API (Flask/FastAPI) để các service khác call.
Next steps:
Trong bài tiếp theo, chúng ta sẽ đi sâu vào Data Engineering for ML - nghệ thuật xử lý, làm sạch, và transform data để model học hiệu quả nhất.
Bài viết thuộc series "From Zero to AI Engineer" - Module 4: ML Foundations