模型复杂度与过拟合

用 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 设计机器学习工作流

常见做法:将数据划分为训练集、测试(或开发)集和验证(或留出)集。

用 Python 设计机器学习工作流

在交叉验证中,多次进行训练-测试划分。数据集被分成 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...