Chương trước đã giới thiệu Adaline (Adaptive Linear Neuron) với gradient descent trên MSE; Ch.3 nâng cấp cùng khung code thành Logistic Regression bằng cách thay activation và loss function. Bài này viết logistic regression Python từ đầu — giúp bạn hiểu sklearn không phải "hộp đen".
Mục tiêu
- Implement Logistic Regression bằng gradient descent trong Python thuần.
- So sánh pipeline Adaline (MSE + identity) vs Logistic (log loss + sigmoid).
- Verify implementation khớp với
sklearn.linear_model.LogisticRegression.
Lý thuyết
Adaline recap (Ch.2 → Ch.3 bridge)
Adaline dùng linear activation $\phi(z) = z$ cho output và MSE loss:
$$ J(w) = \frac{1}{2n} \sum_{i=1}^{n} (y^{(i)} - z^{(i)})^2 $$
Gradient descent cập nhật:
$$ w \leftarrow w - \eta \frac{\partial J}{\partial w} $$
Code class AdalineGD có sẵn fit, net_input, activation, predict — Ch.3 override activation và predict cho logistic.
Chuyển Adaline → Logistic: hai thay đổi cốt lõi
- Activation: identity → sigmoid cho xác suất $\hat{p} = \sigma(z)$.
- Loss & gradient: MSE → log loss; gradient mỗi mẫu: $(\hat{p} - y) x$.
Class LogisticRegressionGD kế thừa cấu trúc Adaline:
def activation(self, z):
return 1.0 / (1.0 + np.exp(-np.clip(z, -250, 250)))
def predict(self, X):
return np.where(self.activation(self.net_input(X)) >= 0.5, 1, 0)
np.clip tránh overflow khi $|z|$ rất lớn.
Training loop
Trong mỗi epoch:
- Forward: $z = Xw + b$, $\hat{p} = \sigma(z)$
- Loss: log loss trung bình
- Backward: $\Delta w = \frac{1}{n} X^T (\hat{p} - y)$
- Update: $w \leftarrow w - \eta \Delta w$
Learning rate $\eta$
Quá lớn → oscillate/diverge; quá nhỏ → chậm. plot cost vs epochs để chẩn đoán — cost phải giảm monotonic (gần đúng) khi $\eta$ hợp lý.
Batch vs Mini-batch vs Stochastic
Implementation dùng batch GD (toàn bộ X mỗi epoch). sklearn mặc định dùng solver tối ưu hiện đại (L-BFGS) — nhanh hơn cho dataset nhỏ-vừa.
Code Python
Implementation đầy đủ, train trên Iris:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression as SklearnLR
from sklearn.metrics import accuracy_score
class LogisticRegressionGD:
"""Logistic Regression — gradient descent."""
def __init__(self, eta=0.01, n_iter=100, random_state=1):
self.eta = eta
self.n_iter = n_iter
self.random_state = random_state
def fit(self, X, y):
rgen = np.random.RandomState(self.random_state)
self.w_ = rgen.normal(loc=0.0, scale=0.01, size=X.shape[1])
self.b_ = np.float64(0.0)
self.losses_ = []
for _ in range(self.n_iter):
net_input = self.net_input(X)
output = self.activation(net_input)
errors = y - output
self.w_ += self.eta * X.T.dot(errors) / X.shape[0]
self.b_ += self.eta * errors.mean()
# Log loss
output = np.clip(output, 1e-10, 1 - 1e-10)
loss = -np.mean(y * np.log(output) + (1 - y) * np.log(1 - output))
self.losses_.append(loss)
return self
def net_input(self, X):
return np.dot(X, self.w_) + self.b_
def activation(self, z):
return 1.0 / (1.0 + np.exp(-np.clip(z, -250, 250)))
def predict(self, X):
return np.where(self.activation(self.net_input(X)) >= 0.5, 1, 0)
def predict_proba_positive(self, X):
return self.activation(self.net_input(X))
# Data
iris = load_iris()
X = iris.data[:, [2, 3]]
y = iris.target
X, y = X[y != 2], y[y != 2]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42, stratify=y
)
scaler = StandardScaler()
X_train_std = scaler.fit_transform(X_train)
X_test_std = scaler.transform(X_test)
# Custom GD
lr_gd = LogisticRegressionGD(eta=0.05, n_iter=1000, random_state=42)
lr_gd.fit(X_train_std, y_train)
acc_custom = accuracy_score(y_test, lr_gd.predict(X_test_std))
# Sklearn reference
lr_sk = SklearnLR(C=1000.0, random_state=42)
lr_sk.fit(X_train_std, y_train)
acc_sk = accuracy_score(y_test, lr_sk.predict(X_test_std))
print(f"Custom GD accuracy: {acc_custom:.3f}")
print(f"Sklearn accuracy: {acc_sk:.3f}")
print(f"Custom weights: {lr_gd.w_}, bias: {lr_gd.b_:.3f}")
print(f"Sklearn weights: {lr_sk.coef_[0]}, bias: {lr_sk.intercept_[0]:.3f}")
plt.plot(range(1, len(lr_gd.losses_) + 1), lr_gd.losses_)
plt.xlabel('Epoch')
plt.ylabel('Log loss')
plt.title('Cost convergence — LogisticRegressionGD')
plt.show()
Lỗi thường gặp
- Quên clip sigmoid input.
exp(-z)overflow khi $z < -700$ → NaN weights. - Cập nhật weight sai dấu. Log loss minimize → gradient descent: $w \leftarrow w - \eta \nabla J$; code viết $w += \eta X^T(errors)/n$ vì
errors = y - output. - Không scale feature. Gradient descent chậm và không ổn định trên Iris raw scale.
- So sánh với sklearn khi chưa hội tụ. Tăng
n_iterhoặc tuneeta. - Dùng MSE activation identity cho classification. Đó là Adaline — không phải logistic.
Bài tập
- Viết class
AdalineGD(MSE) vàLogisticRegressionGD(log loss) cùng interface. Train cả hai trên Iris binary. Model nào phù hợp hơn? Vẽ decision boundary. - Thử
eta = [0.001, 0.01, 0.5, 1.0]. Vẽ loss curve — xác định $\eta$ diverge. - Thêm L2 penalty $\frac{\lambda}{2}|w|^2$ vào loss và gradient update. So sánh overfit khi train trên 20 mẫu, test 130 mẫu.
Tóm tắt
Logistic regression Python là bản nâng cấp tự nhiên từ Adaline: cùng gradient descent framework, khác sigmoid + log loss. Implement tay một lần giúp bạn đọc hiểu solver sklearn và debug convergence.