【问题标题】:How to choose n_estimators in RandomForestClassifier?如何在 RandomForestClassifier 中选择 n_estimators?
【发布时间】:2020-07-01 05:27:29
【问题描述】:

我正在 python 中构建一个随机森林二元分类器,该数据集包含 4898 个实例、60-40 个分层拆分率和 78% 的数据属于一个目标标签,其余数据属于另一个。为了实现最实用/最好的随机森林分类器模型,我应该选择什么值的 n_estimators?我使用下面的代码 sn-p 绘制了准确度与 n_estimators 曲线。 x_trai 和 y_train 分别是训练集中的特征和目标标签,x_test 和 y_test 分别是测试集中的特征和目标标签。

from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
scores =[]
for k in range(1, 200):
    rfc = RandomForestClassifier(n_estimators=k)
    rfc.fit(x_train, y_train)
    y_pred = rfc.predict(x_test)
    scores.append(accuracy_score(y_test, y_pred))

import matplotlib.pyplot as plt
%matplotlib inline

# plot the relationship between K and testing accuracy
# plt.plot(x_axis, y_axis)
plt.plot(range(1, 200), scores)
plt.xlabel('Value of n_estimators for Random Forest Classifier')
plt.ylabel('Testing Accuracy')

在这里,可以看出 n_estimators 的高值会给出一个很好的准确度分数,但即使对于附近的 n_estimators 值,它也会在曲线中随机波动,所以我不能精确地选择最好的。我只想知道n_estimators超参数的调优,应该怎么选,请帮忙。我应该使用 ROC 曲线还是 CAP 曲线而不是 accuracy_score?谢谢。

【问题讨论】:

  • 您应该在性能开始稳定在曲线上的那一刻选择一个值。您不应该尝试选择特定值,n_estimator 的两个接近值之间的性能差异来自随机性导致的可变性,不会复制到新数据中
  • 逐步细化是提高效率的一种方法。尝试使用 GridSearch 和交叉折叠来找到最佳参数

标签: python classification random-forest hyperparameters


【解决方案1】:

在这种情况下不要使用gridsearch - 这是一种矫枉过正的行为 - 而且由于您任意设置参数,您最终可能不会得到不是最佳数字。

scikit-learn 中有一个stage_predict 属性,您可以在每个训练阶段测量验证错误以找到最佳树数。

import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

X_train, X_val, y_train, y_val = train_test_split(X, y)

# try a big number for n_estimator
gbrt = GradientBoostingRegressor(max_depth=2, n_estimators=100)
gbrt.fit(X_train, y_train)

# calculate error on validation set
errors = [mean_squared_error(y_val, y_pred)
 for y_pred in gbrt.staged_predict(X_val)]

bst_n_estimators = np.argmin(errors) + 1
gbrt_best = GradientBoostingRegressor(max_depth=2,n_estimators=bst_n_estimators)
gbrt_best.fit(X_train, y_train)

【讨论】:

    【解决方案2】:

    在一些 n_estimators 之后随机森林会稳定下来是很自然的(因为没有机制来“减慢”拟合不像 boosting)。由于添加更多弱树估计器没有任何好处,您可以选择 50 左右

    【讨论】:

      【解决方案3】:

      查看 (https://github.com/dnishimoto/python-deep-learning/blob/master/Random%20Forest%20Tennis.ipynb) randomsearchcv 示例

      我使用 RandomSearchCV 来找到随机森林分类器的最佳参数

      n_estimators 是要使用的决策树的数量。

      尝试使用 XBBoost 以获得更高的准确性。

      parameter_grid={'n_estimators':[1,2,3,4,5],'max_depth':[2,4,6,8,10],'min_samples_leaf': 
      [1,2,4],'max_features':[1,2,3,4,5,6,7,8]}
      
      number_models=4
      random_RandomForest_class=RandomizedSearchCV(
      estimator=pipeline['clf'],
      param_distributions=parameter_grid,
      n_iter=number_models,
      scoring='accuracy',
      n_jobs=2,
      cv=4,
      refit=True,
      return_train_score=True)
      
      random_RandomForest_class.fit(X_train,y_train)
      predictions=random_RandomForest_class.predict(X)
      
      print("Accuracy Score",accuracy_score(y,predictions));
      print("Best params",random_RandomForest_class.best_params_)
      print("Best score",random_RandomForest_class.best_score_)
      

      【讨论】:

      • 这对我有帮助.. 谢谢!
      猜你喜欢
      • 2021-05-05
      • 2018-03-17
      • 2015-08-10
      • 1970-01-01
      • 1970-01-01
      • 2017-09-24
      • 2016-09-15
      • 2018-02-24
      • 2021-08-20
      相关资源
      最近更新 更多