モデルの複雑さと過学習

Python で設計する Machine Learning ワークフロー

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 で設計する Machine Learning ワークフロー
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 で設計する Machine Learning ワークフロー

標準的にはデータを学習、テスト(開発)、検証(ホールドアウト)に分割する。

Python で設計する Machine Learning ワークフロー

交差検証では学習-テスト分割を複数回行う。データをN分割し、毎回異なるN−1個で学習し、残り1個でテストする。

Python で設計する Machine Learning ワークフロー

交差検証

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 で設計する Machine Learning ワークフロー

モデル複雑さのチューニング

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 で設計する Machine Learning ワークフロー

サンプル内精度は最大深さ3で0.7から始まり、深さ5〜30でほぼ1.0まで上昇。

Python で設計する Machine Learning ワークフロー

サンプル外精度も0.7から開始し、深さ10で0.75に最大化、その後は深さが大きくなると0.7へ低下。

Python で設計する Machine Learning ワークフロー

深さ10以降の範囲が赤で表示され、過学習が発生していることを示す。

Python で設計する Machine Learning ワークフロー

複雑なら良いとは限らない!

Python で設計する Machine Learning ワークフロー

Preparing Video For Download...