Chương 2: Học Thống Kê — 2.2 Đánh Giá Độ Chính Xác Của Mô Hình ISLP §2.2 trang 37–49 ★★★☆☆ Cốt Lõi Chệch-Lệch Bộ Phân Loại Bayes KNN Huấn Luyện vs Kiểm Tra Sách: James, Witten, Hastie, Tibshirani (2023), An Introduction to Statistical Learning with Applications in Python, Springer. # === Google Drive + Colab Tương Thích Đọc Dữ Liệu (Chung Cho Tất Cả Ví Dụ) === import numpy as np import pandas as pd import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures, SplineTransformer from sklearn.neighbors import KNeighborsRegressor, KNeighborsClassifier from sklearn.metrics import mean_squared_error try: from google.colab import drive drive.mount('/content/drive') DATA_PATH = '/content/drive/MyDrive/ISLP_data/' except ImportError: DATA_PATH = '/tmp/' I. Đo Lường Chất Lượng Phù Hợp: MSE trên Tập Huấn Luyện vs MSE trên Tập Kiểm Tra 📚 Cơ Sở Lý Thuyết: MSE xuất phát từ lý thuyết Bình Phương Nhỏ Nhất của Gauss (1809). Từ quan điểm lý thuyết quyết định, MSE là hàm rủi ro dưới hàm mất mát bình phương \(L(Y, \hat{f}(X)) = (Y - \hat{f}(X))^2\). Xem Lehmann & Casella (1998) Theory of Point Estimation §1.6. 1.1 MSE trên Tập Huấn Luyện \[ \text{MSE}_{\text{train}} = \frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{f}(x_i))^2 \quad\text{(Phương trình 2.5)} \] MSE trên tập huấn luyện đo lường lỗi của mô hình trên dữ liệu đã thấy. Tính toán đơn giản, nhưng không thể phản ánh khả năng tổng quát hóa. 1.2 MSE trên Tập Kiểm Tra — Chỉ Số Quan Trọng Thực Sự \[ \text{MSE}_{\text{test}} = \text{Ave}(y_0 - \hat{f}(x_0))^2 \quad\text{(Phương trình 2.6)} \] MSE trên tập kiểm tra đo lường lỗi của mô hình trên dữ liệu chưa thấy. Đây là chỉ số chúng ta thực sự quan tâm. 🎯 Tình Huống Ứng Dụng: Kiểm Tra Lại Mô Hình Giao Dịch Định Lượng Khi các quỹ định lượng trên Phố Wall huấn luyện mô hình giao dịch, nếu chỉ nhìn vào "MSE trên tập huấn luyện" (Sharpe ratio trong mẫu), mô hình có thể quá phù hợp với nhiễu lịch sử. Gerard & Mi (2019) phát hiện, các chiến lược định lượng quá phù hợp có Sharpe ratio ngoài mẫu giảm trung bình hơn 50%. Do đó, trong thực tế phải sử dụng walk-forward validation hoặc expanding window testing. 1.3 Minh Họa Cổ Điển cho MSE trên Tập Huấn Luyện vs Tập Kiểm Tra (Hình 2.9–2.11) # Hình 2.9–2.11 Khái Niệm: MSE trên Tập Huấn Luyện vs Tập Kiểm Tra np.random.seed(42) def simulate_data(n, f_true, sigma=1.0): X = np.sort(np.random.uniform(0, 10, n)) eps = np.random.normal(0, sigma, n) y = f_true(X) + eps return X, y, f_true # Ba hàm thực sự f_nonlinear = lambda x: 0.5 * x + 3 * np.sin(x) + 0.2 * x**2 - 5 f_near_linear = lambda x: 2 + 1.5 * x + 0.1 * np.sin(2*x) f_highly_nonlinear = lambda x: 0.3 * x**2 - x + 10 * np.sin(x) fig, axes = plt.subplots(1, 3, figsize=(18, 5)) titles = ['Hình 2.9: f phi tuyến tính vừa phải', 'Hình 2.10: f gần tuyến tính', 'Hình 2.11: f phi tuyến tính cao'] for ax, title, f_true in zip(axes, titles, [f_nonlinear, f_near_linear, f_highly_nonlinear]): X_train, y_train, _ = simulate_data(30, f_true, sigma=1.5) X_test, y_test, _ = simulate_data(100, f_true, sigma=0) # Đường thực sự x_range = np.linspace(0, 10, 200) ax.plot(x_range, f_true(x_range), 'k-', label='Đường thực sự', linewidth=2) # Phù hợp bậc 1 from sklearn.linear_model import LinearRegression reg1 = LinearRegression().fit(X_train.reshape(-1, 1), y_train) ax.plot(x_range, reg1.predict(x_range.reshape(-1, 1)), 'b--', label='Bậc 1', linewidth=2) # Phù hợp bậc 10 from sklearn.preprocessing import PolynomialFeatures poly10 = PolynomialFeatures(degree=10, include_bias=False) X_train_poly10 = poly10.fit_transform(X_train.reshape(-1, 1)) reg10 = LinearRegression().fit(X_train_poly10, y_train) x_range_poly10 = poly10.transform(x_range.reshape(-1, 1)) ax.plot(x_range, reg10.predict(x_range_poly10), 'g-', label='Bậc 10', linewidth=2) ax.scatter(X_train, y_train, s=30, c='red', alpha=0.5, label='Dữ liệu huấn luyện') ax.set_xlim(0, 10) ax.set_ylim(-5, 10) ax.set_title(title) ax.legend() plt.tight_layout() plt.show()
第 2 章:統計學習 — 2.2 評估模型準確度 ISLP §2.2 pp. 37–49 ★★★☆☆ 核心 Bias-Variance Bayes Classifier KNN 訓練 vs 測試 課本:James, Witten, Hastie, Tibshirani (2023), An Introduction to Statistical Learning with Applications in Python , Springer. # === Google Drive + Colab 相容資料讀取(所有範例共用)=== import numpy as np import pandas as pd import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures, SplineTransformer from sklearn.neighbors import KNeighborsRegressor, KNeighborsClassifier from sklearn.metrics import mean_squared_error try: from google.colab import drive drive.mount('/content/drive') DATA_PATH = '/content/drive/MyDrive/ISLP_data/' except ImportError: DATA_PATH = '/tmp/' 一、衡量配適品質:訓練 MSE vs 測試 MSE 📚 理論基礎 :MSE 源自 Gauss (1809) 的最小平方法理論。從決策理論角度,MSE 是平方損失 \(L(Y, \hat{f}(X)) = (Y - \hat{f}(X))^2\) 下的風險函數。見 Lehmann & Casella (1998) Theory of Point Estimation §1.6。 1.1 訓練 MSE \[ \text{MSE}_{\text{train}} = \frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{f}(x_i))^2 \quad\text{(方程式 2.5)} \] 訓練 MSE 衡量模型在 已見過的資料 上的誤差。計算簡單,但 無法反映泛化能力 。 1.2 測試 MSE —— 真正重要的指標 \[ \text{MSE}_{\text{test}} = \text{Ave}(y_0 - \hat{f}(x_0))^2 \quad\text{(方程式 2.6)} \] 測試 MSE 衡量模型在 未見過的資料 上的誤差。這是我們 真正關心的指標 。 🎯 應用場景:量化交易模型回測 華爾街量化基金訓練交易模型時,若僅看「訓練 MSE」(樣本內 Sharpe ratio),模型可能過度擬合歷史雜訊。Gerard & Mi (2019) 發現,過度擬合的量化策略樣本外 Sharpe ratio 平均衰退 50% 以上。因此實務上必須使用 walk-forward validation 或 expanding window 測試。 1.3 訓練 vs 測試 MSE 的經典示範(Figure 2.9–2.11) # Figure 2.9–2.11 概念:訓練 vs 測試 MSE np.random.seed(42) def simulate_data(n, f_true, sigma=1.0): X = np.sort(np.random.uniform(0, 10, n)) eps = np.random.normal(0, sigma, n) y = f_true(X) + eps return X, y, f_true # 三種真實函數 f_nonlinear = lambda x: 0.5 * x + 3 * np.sin(x) + 0.2 * x**2 - 5 f_near_linear = lambda x: 2 + 1.5 * x + 0.1 * np.sin(2*x) f_highly_nonlinear = lambda x: 0.3 * x**2 - x + 10 * np.sin(x) fig, axes = plt.subplots(1, 3, figsize=(18, 5)) titles = ['Figure 2.9: f 中度非線性', 'Figure