Khi tập huấn luyện có hàng triệu mẫu, batch gradient descent tính gradient trên toàn bộ data mỗi epoch — quá chậm. Stochastic gradient descent (SGD) cập nhật sau từng mẫu (hoặc mini-batch), là cách ML production scale từ Adaline đến deep learning.
Mục tiêu
- Phân biệt batch GD, SGD và mini-batch GD.
- Implement
AdalineSGDonline. - Dùng
sklearn.linear_model.SGDClassifiertrên dữ liệu lớn.
Lý thuyết
Ba biến thể gradient descent
| Phương pháp | Gradient tính trên | Ưu | Nhược |
|---|---|---|---|
| Batch GD | Toàn tập $n$ mẫu | Ổn định, deterministic | $O(n)$ mỗi bước |
| SGD | 1 mẫu | Rẻ, online, escape shallow local min | Nhiễu cao |
| Mini-batch | $k$ mẫu (32–512) | Cân bằng GPU + ổn định | Thêm hyperparameter $k$ |
Deep learning hầu hết dùng mini-batch; AdalineSGD dùng true online (batch size = 1) để minh họa.
Cập nhật SGD cho Adaline
Sau mỗi mẫu $(\mathbf{x}^{(i)}, y^{(i)})$:
$$ \mathbf{w} \leftarrow \mathbf{w} + \eta (y^{(i)} - z^{(i)}) \mathbf{x}^{(i)} $$
$$ b \leftarrow b + \eta (y^{(i)} - z^{(i)}) $$
Shuffle mẫu mỗi epoch giảm bias thứ tự. Learning rate schedule ($\eta$ giảm dần) thường cần cho hội tụ cuối.
Online learning
Mô hình có thể cập nhật liên tục khi stream data mới (click log, sensor) — không cần reload toàn bộ batch. Perceptron rule và Adaline SGD đều online-capable.
Noise và regularization ngầm
Nhiễu gradient SGD đôi khi giúp generalization (tương tự thêm jitter). Không thay thế regularization có chủ đích (L2, dropout) nhưng giải thích vì sao SGD vẫn popular.
sklearn SGDClassifier
Một API cho nhiều loss:
loss="squared_error"— gần Adalineloss="hinge"— linear SVMloss="log_loss"— logistic regression
Tham số quan trọng: eta0, learning_rate (constant, optimal, invscaling), max_iter, penalty, alpha (L2).
Tài liệu: SGD tips.
Scale trước SGD
SGD bắt buộc feature scaling trong hầu hết trường hợp — sklearn cảnh báo nếu bỏ qua. Kết hợp StandardScaler + SGDClassifier trong Pipeline.
Code Python
AdalineSGD
import numpy as np
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
class AdalineSGD:
"""Adaline với online SGD — một mẫu mỗi bước."""
def __init__(self, eta=0.01, n_iter=10, shuffle=True, random_state=1):
self.eta = eta
self.n_iter = n_iter
self.shuffle = shuffle
self.random_state = random_state
def fit(self, X, y):
rgen = np.random.RandomState(self.random_state)
self.w_ = rgen.normal(0.0, 0.01, X.shape[1])
self.b_ = np.float64(0.0)
self.cost_ = []
for epoch in range(self.n_iter):
if self.shuffle:
idx = rgen.permutation(len(y))
X, y = X[idx], y[idx]
total_cost = 0.0
for xi, target in zip(X, y):
z = np.dot(xi, self.w_) + self.b_
error = target - z
self.w_ += self.eta * error * xi
self.b_ += self.eta * error
total_cost += 0.5 * error ** 2
self.cost_.append(total_cost)
return self
def net_input(self, X):
return np.dot(X, self.w_) + self.b_
def predict(self, X):
return np.where(self.net_input(X) >= 0.5, 1, 0)
# --- Demo Iris + so sánh sklearn ---
iris = datasets.load_iris()
X = iris.data[:, [0, 2]]
y = iris.target
mask = y < 2
X, y = X[mask], y[mask].astype(float)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=1, stratify=y
)
scaler = StandardScaler()
X_train_std = scaler.fit_transform(X_train)
X_test_std = scaler.transform(X_test)
# AdalineSGD tự viết
sgd_ada = AdalineSGD(eta=0.01, n_iter=15, random_state=1)
sgd_ada.fit(X_train_std, y_train)
print("AdalineSGD acc:", accuracy_score(y_test, sgd_ada.predict(X_test_std)))
# sklearn SGDClassifier
clf = SGDClassifier(
loss="squared_error",
eta0=0.01,
learning_rate="constant",
max_iter=1000,
tol=1e-3,
random_state=1,
)
clf.fit(X_train_std, y_train)
print("sklearn SGD acc:", accuracy_score(y_test, clf.predict(X_test_std)))
Mini-batch giả lập trên tập lớn
def mini_batch_indices(n_samples, batch_size, rng):
indices = rng.permutation(n_samples)
for start in range(0, n_samples, batch_size):
yield indices[start : start + batch_size]
# Ví dụ: 1000 mẫu giả, batch 32
n, batch_size = 1000, 32
rng = np.random.RandomState(0)
for batch_idx in mini_batch_indices(n, batch_size, rng):
# X_batch = X[batch_idx]; cập nhật w trên batch_idx
pass
Lỗi thường gặp
- Không shuffle: SGD lặp theo thứ tự cố định — dễ gây thiên lệch hội tụ (order bias), đặc biệt khi dữ liệu đã sắp xếp theo lớp.
etaconstant quá lớn về cuối: Cost dao động — thửlearning_rate="invscaling"trong sklearn.- SGD không scale: Convergence kém hoặc cảnh báo sklearn — luôn StandardScaler trước.
- Nhầm
max_itervới epoch × n: sklearn đếm pass; vớipartial_fitsemantics khác — đọc doc kỹ.
Bài tập
- So sánh: Trên Iris scaled, vẽ
cost_củaAdalineGD(batch) vsAdalineSGD— đường nào mượt hơn? - Batch size: Sửa loop cập nhật dùng mini-batch 16 thay vì 1. Ghi nhận thay đổi nhiễu cost.
- Production: Dùng
partial_fitcủaSGDClassifiermô phỏng 3 chunk data liên tiếp (chia train thành 3 phần). Accuracy cuối có bằng fit một lần?
Tóm tắt
Stochastic gradient descent cập nhật tham số từng mẫu hoặc mini-batch — nền scale ML và deep learning. AdalineSGD nối perceptron rule với sklearn SGDClassifier; nhớ shuffle, scale feature và điều chỉnh learning rate.