诊断偏差与方差问题

Python 树模型机器学习

Elie Kawerk

Data Scientist

估计泛化误差

  • 如何估计模型的泛化误差?

  • 不能直接完成,因为:

    • $f$ 未知,

    • 通常只有一个数据集,

    • 噪声不可预测。

Python 树模型机器学习

估计泛化误差

方案:

  • 将数据划分为训练集和测试集,
  • 在训练集上拟合 $\hat{f}$,
  • 在"未见过"的测试集上评估 $\hat{f}$ 的误差。
  • $\hat{f}$ 的泛化误差 ≈ 测试集误差。
Python 树模型机器学习

用交叉验证改进评估

  • 在有把握 $\hat{f}$ 表现前,不应触碰测试集。

  • 在训练集上评估 $\hat{f}$:有偏,因为 $\hat{f}$ 已见过全部训练点。

  • 解决方案 → 交叉验证(CV):

    • K 折交叉验证,

    • 留出法。

Python 树模型机器学习

K 折交叉验证

K 折交叉验证

Python 树模型机器学习

K 折交叉验证

CV 误差

Python 树模型机器学习

诊断方差问题

  • 若 $\hat{f}$ 存在高方差

    $\hat{f}$ 的 CV 误差 > 训练误差。

  • $\hat{f}$ 过拟合训练集。缓解过拟合:
    • 降低模型复杂度,
    • 例如:减小最大深度,增大每叶最小样本数,…
    • 收集更多数据,…
Python 树模型机器学习

诊断偏差问题

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

    $\hat{f}$ 的 CV 误差 ≈ 训练误差 >> 期望误差。

  • $\hat{f}$ 欠拟合训练集。缓解欠拟合:

    • 提高模型复杂度
    • 例如:增大最大深度,减小每叶最小样本数,…
    • 收集更相关的特征
Python 树模型机器学习

在 Auto 数据集上用 sklearn 做 K 折交叉验证

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)
Python 树模型机器学习

在 Auto 数据集上用 sklearn 做 K 折交叉验证

# 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)
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
Python 树模型机器学习

让我们来练习!

Python 树模型机器学习

Preparing Video For Download...