診斷偏差與變異問題

Machine Learning with Tree-Based Models in Python

Elie Kawerk

Data Scientist

估計泛化誤差

  • 我們如何估計模型的泛化誤差?

  • 無法直接做到,因為:

    • $f$ 未知,

    • 通常只有一個資料集,

    • 雜訊不可預測。

Machine Learning with Tree-Based Models in Python

估計泛化誤差

解法:

  • 將資料切成訓練集與測試集,
  • 將 $\hat{f}$ 擬合到訓練集,
  • 在「未看過」的測試集上評估 $\hat{f}$ 的誤差。
  • $\hat{f}$ 的泛化誤差 $\approx$ $\hat{f}$ 的測試集誤差。
Machine Learning with Tree-Based Models in Python

用交叉驗證改進模型評估

  • 在對 $\hat{f}$ 表現有把握前,不要動用測試集。

  • 在訓練集上評估 $\hat{f}$:估計有偏,因為 $\hat{f}$ 已看過所有訓練點。

  • 解法 $\rightarrow$ 交叉驗證(CV):

    • K 折 CV,

    • 留出法 CV。

Machine Learning with Tree-Based Models in Python

K 折 CV

K 折交叉驗證

Machine Learning with Tree-Based Models in Python

K 折 CV

CV 誤差

Machine Learning with Tree-Based Models in Python

診斷變異問題

  • 若 $\hat{f}$ 有「高變異」:

    $\hat{f}$ 的 CV 誤差 > 訓練集誤差。

  • 稱為對訓練集過度擬合。改善過擬合:
    • 降低模型複雜度,
    • 例如:降低最大深度、提高每葉最少樣本數等。
    • 收集更多資料。
Machine Learning with Tree-Based Models in Python

診斷偏差問題

  • 若 $\hat{f}$ 有高偏差:

    $\hat{f}$ 的 CV 誤差 $\approx$ 訓練集誤差 >> 目標誤差。

  • 稱為對訓練集欠擬合。改善欠擬合:

    • 提高模型複雜度,
    • 例如:提高最大深度、降低每葉最少樣本數等。
    • 蒐集更相關的特徵。
Machine Learning with Tree-Based Models in Python

在 sklearn 以 Auto 資料集做 K 折 CV

from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error as MSE
from sklearn.model_selection import cross_val_score

# Set seed for reproducibility SEED = 123 # Split data into 70% train and 30% test X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.3, random_state=SEED)
# Instantiate decision tree regressor and assign it to 'dt' dt = DecisionTreeRegressor(max_depth=4, min_samples_leaf=0.14, random_state=SEED)
Machine Learning with Tree-Based Models in Python

在 sklearn 以 Auto 資料集做 K 折 CV

# Evaluate the list of MSE ontained by 10-fold CV 
# Set n_jobs to -1 in order to exploit all CPU cores in computation
MSE_CV = - cross_val_score(dt, X_train, y_train, cv= 10, 
                           scoring='neg_mean_squared_error',
                           n_jobs = -1)

# Fit 'dt' to the training set dt.fit(X_train, y_train) # Predict the labels of training set y_predict_train = dt.predict(X_train) # Predict the labels of test set y_predict_test = dt.predict(X_test)
Machine Learning with Tree-Based Models in Python
# CV MSE  
print('CV MSE: {:.2f}'.format(MSE_CV.mean()))
CV MSE: 20.51
# Training set MSE
print('Train MSE: {:.2f}'.format(MSE(y_train, y_predict_train)))
Train MSE: 15.30
# Test set MSE
print('Test MSE: {:.2f}'.format(MSE(y_test, y_predict_test)))
Test MSE: 20.92
Machine Learning with Tree-Based Models in Python

一起來練習吧!

Machine Learning with Tree-Based Models in Python

Preparing Video For Download...