Để triển khai Linear Discriminant Analysis đúng, cần nắm rõ scatter matrices — cách đo phương sai trong lớp và giữa các lớp. Bài này theo Chương 5 Python Machine Learning — phần LDA scatter matrices và tiêu chí Fisher.
Mục tiêu
- Định nghĩa và tính $\mathbf{S}_W$, $\mathbf{S}_B$ từ dữ liệu có nhãn.
- Hiểu tiêu chí Fisher $J(\mathbf{w})$ và generalized eigenvalue problem.
- Biết giới hạn $C-1$ discriminant directions trong multi-class LDA.
Lý thuyết
Ký hiệu
- $C$: số lớp.
- $n_c$: số mẫu lớp $c$, $n = \sum_c n_c$.
- $\mathbf{x}_i^{(c)}$: mẫu thứ $i$ của lớp $c$.
- $\boldsymbol{\mu}_c = \frac{1}{n_c}\sum_i \mathbf{x}_i^{(c)}$: mean lớp $c$.
- $\boldsymbol{\mu} = \frac{1}{n}\sum_c n_c \boldsymbol{\mu}_c$: mean toàn cục.
Within-class scatter matrix
Đo độ "spread" của mẫu quanh mean lớp của chúng:
$$\mathbf{S}W = \sum{c=1}^{C} \sum_{i=1}^{n_c} (\mathbf{x}_i^{(c)} - \boldsymbol{\mu}_c)(\mathbf{x}_i^{(c)} - \boldsymbol{\mu}_c)^T$$
Ma trận $d \times d$, đối xứng, positive semi-definite. Phương sai nhỏ trong lớp → mẫu cùng lớp gom cụm chặt → dễ phân tách.
Between-class scatter matrix
Đo khoảng cách giữa các mean lớp so với mean toàn cục:
$$\mathbf{S}B = \sum{c=1}^{C} n_c (\boldsymbol{\mu}_c - \boldsymbol{\mu})(\boldsymbol{\mu}_c - \boldsymbol{\mu})^T$$
Mean các lớp càng xa nhau → $\mathbf{S}_B$ càng "lớn" theo hướng phân tách.
Tiêu chí Fisher (binary)
Với một hướng chiếu $\mathbf{w}$, chiếu scalar $y = \mathbf{w}^T \mathbf{x}$. Fisher tối đa hóa:
$$J(\mathbf{w}) = \frac{(\boldsymbol{\mu}_1' - \boldsymbol{\mu}_2')^2}{(\sigma_1')^2 + (\sigma_2')^2} = \frac{\mathbf{w}^T \mathbf{S}_B \mathbf{w}}{\mathbf{w}^T \mathbf{S}_W \mathbf{w}}$$
Nghiệm: $\mathbf{S}_W^{-1}\mathbf{S}_B \mathbf{w} = \lambda \mathbf{w}$ — generalized eigenvalue problem. Với binary, chỉ cần một eigenvector tương ứng $\lambda$ lớn nhất.
Multi-class LDA
Khi $C > 2$, có tối đa $C-1$ discriminant directions (rank $\mathbf{S}_B \leq C-1$). sklearn giải bằng cách tìm eigenvector của $\mathbf{S}_W^{-1}\mathbf{S}_B$ (hoặc SVD trên ma trận centered per class — xem User guide LDA).
Các direction ortogonal trong không gian Fisher — tương tự PC ortogonal trong PCA nhưng tối ưu theo nhãn.
Regularization
Nếu $\mathbf{S}_W$ singular ( $d > n$ hoặc collinear features), cần regularization. sklearn: solver='lsqr' hoặc 'eigen' với shrinkage='auto' — thêm $\alpha \mathbf{I}$ vào $\mathbf{S}_W$.
LDA vừa giảm chiều vừa classifier
LinearDiscriminantAnalysis trong sklearn còn có thể predict trực tiếp (generative Gaussian assumption per class). Bài này tập trung projection; bài sau cover sklearn API đầy đủ.
Code Python
Tính scatter matrices thủ công trên Iris và đối chiếu với LDA sklearn:
import numpy as np
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
X, y = load_iris(return_X_y=True)
X_std = StandardScaler().fit_transform(X)
classes = np.unique(y)
n_features = X_std.shape[1]
mu_global = X_std.mean(axis=0)
# Within-class scatter
S_W = np.zeros((n_features, n_features))
for c in classes:
X_c = X_std[y == c]
mu_c = X_c.mean(axis=0)
diff = X_c - mu_c
S_W += diff.T @ diff
# Between-class scatter
S_B = np.zeros((n_features, n_features))
for c in classes:
X_c = X_std[y == c]
n_c = len(X_c)
mu_c = X_c.mean(axis=0)
diff = (mu_c - mu_global).reshape(-1, 1)
S_B += n_c * (diff @ diff.T)
print("S_W shape:", S_W.shape)
print("S_B rank (approx):", np.linalg.matrix_rank(S_B))
# Fisher direction via generalized eigen (manual, small d)
eigvals, eigvecs = np.linalg.eig(np.linalg.pinv(S_W) @ S_B)
order = np.argsort(eigvals.real)[::-1]
fisher_dirs = eigvecs[:, order].real
lda = LinearDiscriminantAnalysis(n_components=2)
X_lda = lda.fit_transform(X_std, y)
print("LDA scalings shape:", lda.scalings_.shape)
print("First 2 LD sample coords mean per class:")
for c in classes:
print(f" class {c}:", X_lda[y == c, :2].mean(axis=0))
lda.scalings_ chứa hệ số projection — tương ứng discriminant axes đã chuẩn hóa theo implementation sklearn.
Lỗi thường gặp
- Nhầm $\mathbf{S}_T = \mathbf{S}_W + \mathbf{S}_B$: Total scatter dùng cho PCA; LDA tách riêng within và between.
- Invert $\mathbf{S}_W$ khi singular: Dùng pseudo-inverse hoặc
shrinkage— invert trực tiếp gây NaN. - Quên center/scaling: Scatter đúng trên dữ liệu đã chuẩn hóa; mean lớp và global mean phải nhất quán.
- Yêu cầu quá nhiều components:
n_components > C-1bị sklearn giới hạn hoặc cảnh báo.
Bài tập
- Tự luận: Chứng minh $\mathbf{S}_T = \mathbf{S}_W + \mathbf{S}_B$ với ký hiệu bài học. Ý nghĩa khi PCA dùng $\mathbf{S}_T$?
- Thực hành: Trên Wine, in
matrix_rankcủa $\mathbf{S}_B$. Tại sao rank $\leq 2$ với 3 lớp? - Thử nghiệm: Fit
LinearDiscriminantAnalysis(solver='svd')vssolver='lsqr', shrinkage='auto'trên Breast Cancer ($C=2$). So sánhtransformoutput correlation.
Tóm tắt
Linear Discriminant Analysis dựa trên within-class scatter $\mathbf{S}_W$ và between-class scatter $\mathbf{S}_B$, tối đa hóa Fisher ratio $J(\mathbf{w})$. Multi-class LDA cho tối đa $C-1$ hướng phân biệt. Hiểu scatter matrices là chìa khóa debug và chọn solver phù hợp trong sklearn.
Tiếp tục lộ trình tại khóa Machine Learning cơ bản — bài tiếp theo: LDA projection và sklearn API.