Phần 2 · Nền tảng Machine Learning · Bài 9

Đánh giá model

16:55

Chất lượng của một model phụ thuộc vào cách bạn đo lường nó.

Loại bài: Build
Ngôn ngữ: Python
Cần biết trước: Phase 1 (Probability & Distributions, Statistics for ML), Phase 2 Bài 1-8
Thời gian: ~90 phút

Mục tiêu bài học

  • Tự triển khai K-fold và stratified K-fold cross-validation từ đầu, rồi giải thích vì sao stratification quan trọng với dữ liệu mất cân bằng
  • Tự tính precision, recall, F1, AUC-ROC và các metric cho regression (MSE, RMSE, MAE, R-squared) từ đầu
  • Đọc learning curve để xác định model có high bias hay high variance
  • Nhận diện những lỗi đánh giá thường gặp, gồm data leakage, chọn sai metric và test set contamination

Vấn đề

Bạn đã training một model. Nó đạt accuracy 95% trên dữ liệu của bạn. Vậy nó có tốt không?

Có thể. Cũng có thể không. Nếu 95% dữ liệu thuộc một class, model luôn dự đoán class đó cũng đạt accuracy 95%, dù hoàn toàn vô dụng. Nếu bạn đánh giá trên chính dữ liệu đã dùng để training, con số 95% chẳng có ý nghĩa gì, vì model chỉ ghi nhớ đáp án. Nếu dataset có yếu tố thời gian mà bạn xáo trộn ngẫu nhiên trước khi chia dữ liệu, model có thể đang dùng dữ liệu tương lai để dự đoán quá khứ.

Đánh giá model là chỗ phần lớn dự án ML mắc lỗi. Chọn sai metric khiến model tệ trông có vẻ tốt. Chia dữ liệu sai cho model cơ hội gian lận. So sánh sai khiến bạn chọn model kém hơn. Đánh giá cho đúng là việc bắt buộc. Đó là khác biệt giữa một model hoạt động tốt trong production và một model thất bại ngay khi gặp dữ liệu thực.

Khái niệm

Training, Validation, Test

Sơ đồ

Ba phần dữ liệu, ba mục đích:

  • Training set: model học từ dữ liệu này. Nó thấy các ví dụ này trong quá trình training.
  • Validation set: dùng để điều chỉnh hyperparameter và chọn giữa các model. Model không bao giờ training trên dữ liệu này, nhưng các quyết định của bạn chịu ảnh hưởng từ nó.
  • Test set: chỉ dùng đúng một lần, ở bước cuối cùng, để báo cáo hiệu năng cuối cùng. Nếu bạn xem hiệu năng trên test set rồi quay lại sửa model, nó không còn là test set nữa. Nó đã trở thành validation set thứ hai.

Test set là phần dữ liệu được giữ riêng để bảo đảm hiệu năng bạn báo cáo phản ánh cách model hoạt động trên dữ liệu thực sự chưa từng thấy.

K-Fold Cross-Validation

Với dataset nhỏ, một lần chia train/validation sẽ lãng phí dữ liệu và cho kết quả ước lượng thiếu ổn định. K-fold cross-validation dùng toàn bộ dữ liệu cho cả training lẫn validation:

Sơ đồ
  1. Chia dữ liệu thành KK fold có kích thước bằng nhau
  2. Với mỗi fold, training trên K−1K-1 fold và validation trên fold còn lại
  3. Lấy trung bình điểm validation của KK lần

K=5K=5 hoặc K=10K=10 là những lựa chọn thông dụng. Mỗi điểm dữ liệu được dùng cho validation đúng một lần. Điểm trung bình là ước lượng ổn định hơn kết quả từ bất kỳ lần chia riêng lẻ nào.

Stratified K-fold: giữ nguyên tỷ lệ các class trong mỗi fold. Nếu dataset có 70% thuộc class A và 30% thuộc class B, mỗi fold sẽ có tỷ lệ gần như vậy. Điều này quan trọng với dataset mất cân bằng, vì cách chia ngẫu nhiên có thể dồn toàn bộ mẫu của class thiểu số vào một fold.

Metric cho Classification

Confusion matrix là nền tảng. Với binary classification:

Dự đoán PositiveDự đoán Negative
Thực tế PositiveTrue Positive (TP)False Negative (FN)
Thực tế NegativeFalse Positive (FP)True Negative (TN)

Từ bảng này, ta có các metric còn lại:

  • Accuracy = (TP+TN)/(TP+TN+FP+FN)(TP + TN) / (TP + TN + FP + FN). Tỷ lệ dự đoán đúng. Dễ gây hiểu lầm khi các class mất cân bằng.
  • Precision = TP/(TP+FP)TP / (TP + FP). Trong tất cả trường hợp được dự đoán là positive, có bao nhiêu trường hợp thực sự là positive? Dùng khi false positive gây tốn kém, chẳng hạn bộ lọc spam đánh dấu email thật là spam.
  • Recall (sensitivity) = TP/(TP+FN)TP / (TP + FN). Trong tất cả trường hợp thực sự là positive, ta phát hiện được bao nhiêu? Dùng khi false negative gây tốn kém, chẳng hạn tầm soát ung thư nhưng bỏ sót khối u.
  • F1 score = 2⋅precision⋅recall/(precision+recall)2 \cdot \text{precision} \cdot \text{recall} / (\text{precision} + \text{recall}). Trung bình điều hòa của precision và recall. Cân bằng cả hai khi không metric nào rõ ràng quan trọng hơn.
  • AUC-ROC: diện tích dưới đường cong Receiver Operating Characteristic. Đường cong biểu diễn true positive rate so với false positive rate ở nhiều ngưỡng classification khác nhau. AUC = 0.5 nghĩa là đoán ngẫu nhiên, AUC = 1.0 nghĩa là phân tách hoàn hảo. Metric này không phụ thuộc vào ngưỡng: nó đo khả năng model xếp các trường hợp positive cao hơn các trường hợp negative, bất kể bạn chọn ngưỡng cắt nào.

Metric cho Regression

  • MSE (Mean Squared Error) = mean((ytrue−ypred)2)\text{mean}((y_{\text{true}} - y_{\text{pred}})^2). Phạt lỗi lớn theo bình phương. Nhạy với outlier.
  • RMSE (Root Mean Squared Error) = MSE\sqrt{\text{MSE}}. Có cùng đơn vị với biến mục tiêu. Dễ diễn giải hơn MSE.
  • MAE (Mean Absolute Error) = mean(∣ytrue−ypred∣)\text{mean}(\lvert y_{\text{true}} - y_{\text{pred}} \rvert). Tính mọi lỗi theo tỷ lệ tuyến tính. Ít bị ảnh hưởng bởi outlier hơn MSE.
  • R-squared = 1−SSres/SStot1 - SS_{\text{res}} / SS_{\text{tot}}, trong đó SSres=∑(ytrue−ypred)2SS_{\text{res}} = \sum (y_{\text{true}} - y_{\text{pred}})^2 và SStot=∑(ytrue−ymean)2SS_{\text{tot}} = \sum (y_{\text{true}} - y_{\text{mean}})^2. Tỷ lệ phương sai được model giải thích. R2=1.0R^2 = 1.0 là hoàn hảo. R2=0.0R^2 = 0.0 nghĩa là model không tốt hơn việc luôn dự đoán giá trị trung bình. R2R^2 có thể âm nếu model còn tệ hơn cách dự đoán giá trị trung bình.

Learning Curves

Vẽ điểm training và validation theo kích thước training set:

  • High bias (underfitting): cả hai đường cong hội tụ ở mức điểm thấp. Thêm dữ liệu sẽ không giúp ích. Bạn cần một model phức tạp hơn.
  • High variance (overfitting): điểm training cao nhưng điểm validation thấp hơn nhiều. Khoảng cách giữa hai đường cong lớn. Thêm dữ liệu có thể giúp ích.

Validation Curves

Vẽ điểm training và validation theo giá trị của một hyperparameter:

  • Ở độ phức tạp thấp: cả hai điểm đều thấp (underfitting)
  • Ở độ phức tạp phù hợp: cả hai điểm đều cao và gần nhau
  • Ở độ phức tạp cao: điểm training vẫn cao nhưng điểm validation giảm (overfitting)

Giá trị hyperparameter tối ưu là điểm mà điểm validation đạt cao nhất.

Những lỗi đánh giá thường gặp

Data leakage: thông tin từ test set lọt vào quá trình training. Ví dụ: fit scaler trên toàn bộ dataset trước khi chia dữ liệu, đưa dữ liệu tương lai vào bài toán dự đoán chuỗi thời gian, hoặc dùng một feature được tạo từ biến mục tiêu. Luôn chia dữ liệu trước, rồi mới tiền xử lý.

Mất cân bằng giữa các class: 99% giao dịch là hợp lệ, 1% là gian lận. Model luôn dự đoán “hợp lệ” cũng đạt accuracy 99%. Hãy dùng precision, recall, F1 hoặc AUC-ROC.

Chọn sai metric: tối ưu accuracy khi thứ bạn cần tối ưu là recall (chẩn đoán y khoa), hoặc tối ưu RMSE khi dữ liệu có nhiều outlier lớn (khi đó hãy dùng MAE).

Không dùng stratified split: với dữ liệu mất cân bằng, cách chia ngẫu nhiên có thể để quá ít mẫu của class thiểu số trong validation fold, khiến kết quả ước lượng thiếu ổn định.

Kiểm tra quá thường xuyên: mỗi lần xem hiệu năng trên test set rồi điều chỉnh model, bạn lại overfit vào test set. Test set chỉ dùng một lần.

Tự xây dựng

Bước 1: Chia train/validation/test

python
import random
import math


def train_val_test_split(X, y, train_ratio=0.6, val_ratio=0.2, seed=42):
    random.seed(seed)
    n = len(X)
    indices = list(range(n))
    random.shuffle(indices)

    train_end = int(n * train_ratio)
    val_end = int(n * (train_ratio + val_ratio))

    train_idx = indices[:train_end]
    val_idx = indices[train_end:val_end]
    test_idx = indices[val_end:]

    X_train = [X[i] for i in train_idx]
    y_train = [y[i] for i in train_idx]
    X_val = [X[i] for i in val_idx]
    y_val = [y[i] for i in val_idx]
    X_test = [X[i] for i in test_idx]
    y_test = [y[i] for i in test_idx]

    return X_train, y_train, X_val, y_val, X_test, y_test

Bước 2: K-fold và stratified K-fold cross-validation

python
def kfold_split(n, k=5, seed=42):
    random.seed(seed)
    indices = list(range(n))
    random.shuffle(indices)

    fold_size = n // k
    folds = []

    for i in range(k):
        start = i * fold_size
        end = start + fold_size if i < k - 1 else n
        val_idx = indices[start:end]
        train_idx = indices[:start] + indices[end:]
        folds.append((train_idx, val_idx))

    return folds


def stratified_kfold_split(y, k=5, seed=42):
    random.seed(seed)

    class_indices = {}
    for i, label in enumerate(y):
        class_indices.setdefault(label, []).append(i)

    for label in class_indices:
        random.shuffle(class_indices[label])

    folds = [{"train": [], "val": []} for _ in range(k)]

    for label, indices in class_indices.items():
        fold_size = len(indices) // k
        for i in range(k):
            start = i * fold_size
            end = start + fold_size if i < k - 1 else len(indices)
            val_part = indices[start:end]
            train_part = indices[:start] + indices[end:]
            folds[i]["val"].extend(val_part)
            folds[i]["train"].extend(train_part)

    return [(f["train"], f["val"]) for f in folds]


def cross_validate(X, y, model_fn, k=5, metric_fn=None, stratified=False):
    n = len(X)

    if stratified:
        folds = stratified_kfold_split(y, k)
    else:
        folds = kfold_split(n, k)

    scores = []
    for train_idx, val_idx in folds:
        X_train = [X[i] for i in train_idx]
        y_train = [y[i] for i in train_idx]
        X_val = [X[i] for i in val_idx]
        y_val = [y[i] for i in val_idx]

        model = model_fn()
        model.fit(X_train, y_train)
        predictions = [model.predict(x) for x in X_val]

        if metric_fn:
            score = metric_fn(y_val, predictions)
        else:
            score = sum(1 for yt, yp in zip(y_val, predictions) if yt == yp) / len(y_val)
        scores.append(score)

    return scores

Bước 3: Confusion matrix và các metric cho classification

python
def confusion_matrix(y_true, y_pred):
    tp = sum(1 for yt, yp in zip(y_true, y_pred) if yt == 1 and yp == 1)
    tn = sum(1 for yt, yp in zip(y_true, y_pred) if yt == 0 and yp == 0)
    fp = sum(1 for yt, yp in zip(y_true, y_pred) if yt == 0 and yp == 1)
    fn = sum(1 for yt, yp in zip(y_true, y_pred) if yt == 1 and yp == 0)
    return tp, tn, fp, fn


def accuracy(y_true, y_pred):
    tp, tn, fp, fn = confusion_matrix(y_true, y_pred)
    total = tp + tn + fp + fn
    return (tp + tn) / total if total > 0 else 0.0


def precision(y_true, y_pred):
    tp, tn, fp, fn = confusion_matrix(y_true, y_pred)
    return tp / (tp + fp) if (tp + fp) > 0 else 0.0


def recall(y_true, y_pred):
    tp, tn, fp, fn = confusion_matrix(y_true, y_pred)
    return tp / (tp + fn) if (tp + fn) > 0 else 0.0


def f1_score(y_true, y_pred):
    p = precision(y_true, y_pred)
    r = recall(y_true, y_pred)
    return 2 * p * r / (p + r) if (p + r) > 0 else 0.0


def roc_curve(y_true, y_scores):
    thresholds = sorted(set(y_scores), reverse=True)
    tpr_list = []
    fpr_list = []

    total_positives = sum(y_true)
    total_negatives = len(y_true) - total_positives

    for threshold in thresholds:
        y_pred = [1 if s >= threshold else 0 for s in y_scores]
        tp = sum(1 for yt, yp in zip(y_true, y_pred) if yt == 1 and yp == 1)
        fp = sum(1 for yt, yp in zip(y_true, y_pred) if yt == 0 and yp == 1)

        tpr = tp / total_positives if total_positives > 0 else 0.0
        fpr = fp / total_negatives if total_negatives > 0 else 0.0

        tpr_list.append(tpr)
        fpr_list.append(fpr)

    return fpr_list, tpr_list, thresholds


def auc_roc(y_true, y_scores):
    fpr_list, tpr_list, _ = roc_curve(y_true, y_scores)

    pairs = sorted(zip(fpr_list, tpr_list))
    fpr_sorted = [p[0] for p in pairs]
    tpr_sorted = [p[1] for p in pairs]

    area = 0.0
    for i in range(1, len(fpr_sorted)):
        width = fpr_sorted[i] - fpr_sorted[i - 1]
        height = (tpr_sorted[i] + tpr_sorted[i - 1]) / 2
        area += width * height

    return area

Bước 4: Các metric cho regression

python
def mse(y_true, y_pred):
    n = len(y_true)
    return sum((yt - yp) ** 2 for yt, yp in zip(y_true, y_pred)) / n


def rmse(y_true, y_pred):
    return math.sqrt(mse(y_true, y_pred))


def mae(y_true, y_pred):
    n = len(y_true)
    return sum(abs(yt - yp) for yt, yp in zip(y_true, y_pred)) / n


def r_squared(y_true, y_pred):
    mean_y = sum(y_true) / len(y_true)
    ss_res = sum((yt - yp) ** 2 for yt, yp in zip(y_true, y_pred))
    ss_tot = sum((yt - mean_y) ** 2 for yt in y_true)
    if ss_tot == 0:
        return 0.0
    return 1.0 - ss_res / ss_tot

Bước 5: Learning curves

python
def learning_curve(X, y, model_fn, metric_fn, train_sizes=None, val_ratio=0.2, seed=42):
    random.seed(seed)
    n = len(X)
    indices = list(range(n))
    random.shuffle(indices)

    val_size = int(n * val_ratio)
    val_idx = indices[:val_size]
    pool_idx = indices[val_size:]

    X_val = [X[i] for i in val_idx]
    y_val = [y[i] for i in val_idx]

    if train_sizes is None:
        train_sizes = [int(len(pool_idx) * r) for r in [0.1, 0.2, 0.4, 0.6, 0.8, 1.0]]

    train_scores = []
    val_scores = []

    for size in train_sizes:
        subset = pool_idx[:size]
        X_train = [X[i] for i in subset]
        y_train = [y[i] for i in subset]

        model = model_fn()
        model.fit(X_train, y_train)

        train_pred = [model.predict(x) for x in X_train]
        val_pred = [model.predict(x) for x in X_val]

        train_scores.append(metric_fn(y_train, train_pred))
        val_scores.append(metric_fn(y_val, val_pred))

    return train_sizes, train_scores, val_scores

Bước 6: Một classifier đơn giản để kiểm thử, cùng bản demo đầy đủ

python
class SimpleLogistic:
    def __init__(self, lr=0.1, epochs=100):
        self.lr = lr
        self.epochs = epochs
        self.weights = None
        self.bias = 0.0

    def sigmoid(self, z):
        z = max(-500, min(500, z))
        return 1.0 / (1.0 + math.exp(-z))

    def fit(self, X, y):
        n_features = len(X[0])
        self.weights = [0.0] * n_features
        self.bias = 0.0

        for _ in range(self.epochs):
            for xi, yi in zip(X, y):
                z = sum(w * x for w, x in zip(self.weights, xi)) + self.bias
                pred = self.sigmoid(z)
                error = yi - pred
                for j in range(n_features):
                    self.weights[j] += self.lr * error * xi[j]
                self.bias += self.lr * error

    def predict_proba(self, x):
        z = sum(w * xi for w, xi in zip(self.weights, x)) + self.bias
        return self.sigmoid(z)

    def predict(self, x):
        return 1 if self.predict_proba(x) >= 0.5 else 0


class SimpleLinearRegression:
    def __init__(self, lr=0.001, epochs=200):
        self.lr = lr
        self.epochs = epochs
        self.weights = None
        self.bias = 0.0

    def fit(self, X, y):
        n_features = len(X[0])
        self.weights = [0.0] * n_features
        self.bias = 0.0
        n = len(X)

        for _ in range(self.epochs):
            for xi, yi in zip(X, y):
                pred = sum(w * x for w, x in zip(self.weights, xi)) + self.bias
                error = yi - pred
                for j in range(n_features):
                    self.weights[j] += self.lr * error * xi[j] / n
                self.bias += self.lr * error / n

    def predict(self, x):
        return sum(w * xi for w, xi in zip(self.weights, x)) + self.bias


def standardize(values):
    n = len(values)
    mean = sum(values) / n
    var = sum((v - mean) ** 2 for v in values) / n
    std = math.sqrt(var) if var > 0 else 1.0
    return [(v - mean) / std for v in values], mean, std


def make_classification_data(n=300, seed=42):
    random.seed(seed)
    X = []
    y = []
    for _ in range(n):
        x1 = random.gauss(0, 1)
        x2 = random.gauss(0, 1)
        label = 1 if (x1 + x2 + random.gauss(0, 0.5)) > 0 else 0
        X.append([x1, x2])
        y.append(label)
    return X, y


def make_regression_data(n=200, seed=42):
    random.seed(seed)
    X = []
    y = []
    for _ in range(n):
        x1 = random.uniform(0, 10)
        x2 = random.uniform(0, 5)
        target = 3 * x1 + 2 * x2 + random.gauss(0, 2)
        X.append([x1, x2])
        y.append(target)
    return X, y


def make_imbalanced_data(n=300, minority_ratio=0.05, seed=42):
    random.seed(seed)
    X = []
    y = []
    for _ in range(n):
        if random.random() < minority_ratio:
            x1 = random.gauss(3, 0.5)
            x2 = random.gauss(3, 0.5)
            label = 1
        else:
            x1 = random.gauss(0, 1)
            x2 = random.gauss(0, 1)
            label = 0
        X.append([x1, x2])
        y.append(label)
    return X, y


if __name__ == "__main__":
    X_clf, y_clf = make_classification_data(300)

    print("=== Train/Validation/Test Split ===")
    X_train, y_train, X_val, y_val, X_test, y_test = train_val_test_split(X_clf, y_clf)
    print(f"  Train: {len(X_train)}, Val: {len(X_val)}, Test: {len(X_test)}")
    print(f"  Train class distribution: {sum(y_train)}/{len(y_train)} positive")
    print(f"  Val class distribution: {sum(y_val)}/{len(y_val)} positive")

    model = SimpleLogistic(lr=0.1, epochs=200)
    model.fit(X_train, y_train)

    print("\n=== Classification Metrics ===")
    y_pred = [model.predict(x) for x in X_test]
    tp, tn, fp, fn = confusion_matrix(y_test, y_pred)
    print(f"  Confusion matrix: TP={tp}, TN={tn}, FP={fp}, FN={fn}")
    print(f"  Accuracy:  {accuracy(y_test, y_pred):.4f}")
    print(f"  Precision: {precision(y_test, y_pred):.4f}")
    print(f"  Recall:    {recall(y_test, y_pred):.4f}")
    print(f"  F1 Score:  {f1_score(y_test, y_pred):.4f}")

    y_scores = [model.predict_proba(x) for x in X_test]
    auc = auc_roc(y_test, y_scores)
    print(f"  AUC-ROC:   {auc:.4f}")

    print("\n=== K-Fold Cross-Validation (K=5) ===")
    cv_scores = cross_validate(
        X_clf, y_clf,
        model_fn=lambda: SimpleLogistic(lr=0.1, epochs=200),
        k=5,
        metric_fn=accuracy,
    )
    mean_cv = sum(cv_scores) / len(cv_scores)
    std_cv = math.sqrt(sum((s - mean_cv) ** 2 for s in cv_scores) / len(cv_scores))
    print(f"  Fold scores: {[round(s, 4) for s in cv_scores]}")
    print(f"  Mean: {mean_cv:.4f} (+/- {std_cv:.4f})")

    print("\n=== Stratified K-Fold Cross-Validation (K=5) ===")
    strat_scores = cross_validate(
        X_clf, y_clf,
        model_fn=lambda: SimpleLogistic(lr=0.1, epochs=200),
        k=5,
        metric_fn=accuracy,
        stratified=True,
    )
    strat_mean = sum(strat_scores) / len(strat_scores)
    strat_std = math.sqrt(sum((s - strat_mean) ** 2 for s in strat_scores) / len(strat_scores))
    print(f"  Fold scores: {[round(s, 4) for s in strat_scores]}")
    print(f"  Mean: {strat_mean:.4f} (+/- {strat_std:.4f})")

    print("\n=== Imbalanced Data: Why Accuracy Lies ===")
    X_imb, y_imb = make_imbalanced_data(300, minority_ratio=0.05)
    positives = sum(y_imb)
    print(f"  Class distribution: {positives} positive, {len(y_imb) - positives} negative ({positives/len(y_imb)*100:.1f}% positive)")

    always_negative = [0] * len(y_imb)
    print(f"  Always-negative baseline:")
    print(f"    Accuracy:  {accuracy(y_imb, always_negative):.4f}")
    print(f"    Precision: {precision(y_imb, always_negative):.4f}")
    print(f"    Recall:    {recall(y_imb, always_negative):.4f}")
    print(f"    F1 Score:  {f1_score(y_imb, always_negative):.4f}")

    X_tr_i, y_tr_i, X_v_i, y_v_i, X_te_i, y_te_i = train_val_test_split(X_imb, y_imb)
    model_imb = SimpleLogistic(lr=0.5, epochs=500)
    model_imb.fit(X_tr_i, y_tr_i)
    y_pred_imb = [model_imb.predict(x) for x in X_te_i]
    print(f"\n  Trained model on imbalanced data:")
    print(f"    Accuracy:  {accuracy(y_te_i, y_pred_imb):.4f}")
    print(f"    Precision: {precision(y_te_i, y_pred_imb):.4f}")
    print(f"    Recall:    {recall(y_te_i, y_pred_imb):.4f}")
    print(f"    F1 Score:  {f1_score(y_te_i, y_pred_imb):.4f}")

    print("\n=== Regression Metrics ===")
    X_reg, y_reg = make_regression_data(200)

    col0 = [x[0] for x in X_reg]
    col1 = [x[1] for x in X_reg]
    col0_s, m0, s0 = standardize(col0)
    col1_s, m1, s1 = standardize(col1)
    X_reg_scaled = [[col0_s[i], col1_s[i]] for i in range(len(X_reg))]

    X_tr_r, y_tr_r, X_v_r, y_v_r, X_te_r, y_te_r = train_val_test_split(X_reg_scaled, y_reg)
    reg_model = SimpleLinearRegression(lr=0.01, epochs=500)
    reg_model.fit(X_tr_r, y_tr_r)
    y_pred_r = [reg_model.predict(x) for x in X_te_r]

    print(f"  MSE:       {mse(y_te_r, y_pred_r):.4f}")
    print(f"  RMSE:      {rmse(y_te_r, y_pred_r):.4f}")
    print(f"  MAE:       {mae(y_te_r, y_pred_r):.4f}")
    print(f"  R-squared: {r_squared(y_te_r, y_pred_r):.4f}")

    mean_baseline = [sum(y_tr_r) / len(y_tr_r)] * len(y_te_r)
    print(f"\n  Mean baseline:")
    print(f"    MSE:       {mse(y_te_r, mean_baseline):.4f}")
    print(f"    R-squared: {r_squared(y_te_r, mean_baseline):.4f}")

    print("\n=== Learning Curve ===")
    sizes, train_sc, val_sc = learning_curve(
        X_clf, y_clf,
        model_fn=lambda: SimpleLogistic(lr=0.1, epochs=200),
        metric_fn=accuracy,
    )
    print(f"  {'Size':>6} {'Train':>8} {'Val':>8}")
    for s, tr, va in zip(sizes, train_sc, val_sc):
        print(f"  {s:>6} {tr:>8.4f} {va:>8.4f}")

    print("\n=== Statistical Model Comparison ===")
    model_a_scores = cross_validate(
        X_clf, y_clf,
        model_fn=lambda: SimpleLogistic(lr=0.1, epochs=100),
        k=5, metric_fn=accuracy,
    )
    model_b_scores = cross_validate(
        X_clf, y_clf,
        model_fn=lambda: SimpleLogistic(lr=0.1, epochs=500),
        k=5, metric_fn=accuracy,
    )
    diffs = [a - b for a, b in zip(model_a_scores, model_b_scores)]
    mean_diff = sum(diffs) / len(diffs)
    std_diff = math.sqrt(sum((d - mean_diff) ** 2 for d in diffs) / len(diffs))
    t_stat = mean_diff / (std_diff / math.sqrt(len(diffs))) if std_diff > 0 else 0.0
    print(f"  Model A (100 epochs) mean: {sum(model_a_scores)/len(model_a_scores):.4f}")
    print(f"  Model B (500 epochs) mean: {sum(model_b_scores)/len(model_b_scores):.4f}")
    print(f"  Mean difference: {mean_diff:.4f}")
    print(f"  Paired t-statistic: {t_stat:.4f}")
    print(f"  (|t| > 2.78 for significance at p<0.05 with df=4)")

Dùng thực tế

Với scikit-learn, việc đánh giá đã được tích hợp vào quy trình làm việc:

python
from sklearn.model_selection import cross_val_score, StratifiedKFold, learning_curve
from sklearn.metrics import (
    accuracy_score, precision_score, recall_score, f1_score,
    roc_auc_score, confusion_matrix, mean_squared_error, r2_score,
)
from sklearn.linear_model import LogisticRegression

model = LogisticRegression()
scores = cross_val_score(model, X, y, cv=StratifiedKFold(5), scoring="f1")

Các phiên bản tự xây dựng cho bạn thấy chính xác cross-validation làm gì (không có phép màu nào, chỉ có vòng lặp for và việc theo dõi index), cách tính từng metric (chỉ cần đếm TP/FP/TN/FN), và vì sao stratification quan trọng (giữ tỷ lệ class trong mỗi fold). Các phiên bản trong thư viện có thêm khả năng chạy song song, nhiều lựa chọn tính điểm hơn và khả năng tích hợp với pipeline.

Đưa vào sản phẩm

Bài học này tạo ra:

  • outputs/skill-evaluation.md - một skill về chiến lược đánh giá model classification và regression

Bài tập

  1. Triển khai precision-recall curve: vẽ precision so với recall ở các ngưỡng khác nhau. Tính average precision (diện tích dưới PR curve). So sánh PR curve với ROC curve trên một dataset mất cân bằng và giải thích khi nào mỗi đường cong cung cấp nhiều thông tin hơn.
  2. Xây dựng vòng lặp nested cross-validation: vòng ngoài đánh giá hiệu năng model, vòng trong điều chỉnh hyperparameter. Dùng nó để so sánh công bằng hai model mà không để dữ liệu validation lọt vào quá trình đánh giá.
  3. Triển khai permutation test để so sánh model: xáo trộn các label, training lại và đo hiệu năng. Lặp lại 100 lần để tạo một phân phối khi không có mối liên hệ thật. Tính p-value của hiệu năng model quan sát được so với phân phối này.

Thuật ngữ chính

Thuật ngữNgười ta hay nóiNghĩa thật sự
Overfitting“Ghi nhớ dữ liệu training”Model học cả nhiễu trong dữ liệu training, nên hoạt động tốt trên dữ liệu training nhưng kém trên dữ liệu chưa từng thấy
Cross-validation“Kiểm thử trên các tập con khác nhau”Luân phiên một cách có hệ thống phần dữ liệu dùng cho validation, rồi lấy trung bình kết quả của tất cả các lượt
Precision“Có bao nhiêu dự đoán positive là đúng”TP/(TP+FP)TP / (TP + FP): tỷ lệ dự đoán positive mà thực tế cũng là positive
Recall“Ta tìm được bao nhiêu trường hợp thực sự positive”TP/(TP+FN)TP / (TP + FN): tỷ lệ trường hợp thực sự positive được xác định đúng
AUC-ROC“Model phân tách các class tốt đến đâu”Diện tích dưới đường cong true positive rate so với false positive rate qua mọi ngưỡng, từ 0.5 (ngẫu nhiên) đến 1.0 (hoàn hảo)
R-squared“Giải thích được bao nhiêu phương sai”1−(sum of squared residuals/total sum of squares)1 - (\text{sum of squared residuals} / \text{total sum of squares}): tỷ lệ phương sai của biến mục tiêu mà model nắm bắt được
Data leakage“Model đã gian lận”Dùng trong quá trình training thông tin vốn không có tại thời điểm dự đoán, khiến kết quả đánh giá lạc quan hơn thực tế
Learning curve“Hiệu năng thay đổi ra sao khi có thêm dữ liệu”Đồ thị điểm training và validation theo kích thước training set, cho thấy underfitting hoặc overfitting
Stratified split“Giữ cân bằng tỷ lệ các class”Chia dữ liệu sao cho mỗi tập con có tỷ lệ từng class giống toàn bộ dataset

Đọc thêm