如何在RandomForestClassifier中选择n_estimators?

问题描述 投票:0回答:4

我正在 python 中的一个预处理数据集上构建一个随机森林二元分类器,该数据集包含 4898 个实例、60-40 分层分割比和 78% 的数据属于一个目标标签,其余数据属于另一个目标标签。为了实现最实用/最好的随机森林分类器模型,我应该选择什么值的 n_estimators ?我使用下面的代码片段绘制了准确性与 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
吗?谢谢。

python classification random-forest hyperparameters
4个回答
0
投票

参见(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_)

0
投票

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


0
投票

在这种情况下不要使用

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)

-1
投票

只有我或其他已经回答过这个问题的人并没有真正回答你的问题吗?如果您仍在寻找如何获得所需的准确度分数和 n_estimator 的答案。我也许可以回答。

首先,您已经从代码中回答了这个问题。

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))

如您所见,您已经将accuracy_score保存到了

scores
中。所以你只需要通过从 socres 列表中找到最大值来调用它即可。

maxs = max(scores)
maxs_idx = scores.index(maxs)

然后只需将打印命令放在最后几行即可。

print(f"Accuracy Score: {maxs} with n_estimators: {maxs_idx}")

我希望您的问题已经得到解决。好吧,我也感谢你,因为你的代码也帮助我创建了一种找到最佳估计器的方法。

© www.soinside.com 2019 - 2024. All rights reserved.