模型複雜度與過度擬合

在 Python 設計機器學習工作流程

Dr. Chris Anagnostopoulos

Honorary Associate Professor

什麼是模型複雜度?

RandomForestClassifier() 可接受額外參數,例如 max_depth

help(RandomForestClassifier)
Help on class RandomForestClassifier in module sklearn.ensemble.forest:
...
 |  max_depth : integer or None, optional (default=None)
 |      The maximum depth of the tree. If None, then nodes are expanded until
 |      all leaves are pure or until all leaves contain less than
 |      min_samples_split samples.
在 Python 設計機器學習工作流程
m2 = RandomForestClassifier(
    max_depth=2)
m2.fit(X_train, y_train)

m2.estimators_[0]

深度為 2 的決策樹。

m4 = RandomForestClassifier(
    max_depth=4)
m4.fit(X_train, y_train)

m4.estimators_[0]

深度為 4 的決策樹。

在 Python 設計機器學習工作流程

標準做法是將資料分成 training、test(或 development)與 validation(或 hold-out)。

在 Python 設計機器學習工作流程

在交叉驗證中會多次進行 train-test 切分。將資料集分成 N 份,每次用不同的 N-1 份做訓練,剩下 1 份做測試。

在 Python 設計機器學習工作流程

交叉驗證

cross_val_score() 評估準確率:

from sklearn.model_selection import cross_val_score

cross_val_score(RandomForestClassifier(), X, y)
array([0.7218 , 0.7682, 0.7866])
numpy.mean(cross_val_score(RandomForestClassifier(), X, y))
0.7589
在 Python 設計機器學習工作流程

調整模型複雜度

GridSearchCV() 微調樹的深度:

from sklearn.model_selection import GridSearchCV
param_grid = {'max_depth':[5,10,20]}
grid = GridSearchCV(RandomForestClassifier(), param_grid)
grid.fit(X,y)
grid._best_params
{'max_depth': 10}
在 Python 設計機器學習工作流程

樣本內準確率在最大深度 3 時為 0.7,隨深度從 5 增至 30 幾乎升到 1.0。

在 Python 設計機器學習工作流程

樣本外準確率同樣從 0.7 起,在深度 10 達到 0.75,之後更大深度又回到 0.7。

在 Python 設計機器學習工作流程

從深度 10 起之區間以紅色標示,表示發生過度擬合。

在 Python 設計機器學習工作流程

更複雜不一定更好!

在 Python 設計機器學習工作流程

Preparing Video For Download...