为什么使用 cross_val_score 为 RandomForestClassifier 调整 n_estimators 时会产生错误?

WHy an error is generated when tuning n_estimators for RandomForestClassifier using cross_val_score?

我正在处理一个不平衡的数据,使用欠采样,我使两者 类 的比例相同。

X_undersample dataframe (984,28)
y_undersample dataframe(984,1)

我正在使用随机森林分类器,以便找到最佳参数 n_estimators我正在使用交叉验证。这是下面的代码。

j_shout=range(1,300)
j_acc=[]
for j in j_shout: 
   lr = RandomForestClassifier(n_estimators = j, criterion = 'entropy', random_state = 0)
   score=cross_val_score(lr,X_undersample,y_undersample,cv=10,scoring='accuracy')
   print ('iteration',j,':cross_validation accuracy=',score)
   j_acc.append(score.mean())

现在,当我 运行 出现以下错误时。

File "<ipython-input-43-954a9717dcea>", line 5, in <module>
    score=cross_val_score(lr,X_undersample,y_undersample,cv=10,scoring='accuracy')

  File "D:\installations\AC\lib\site-packages\sklearn\cross_validation.py", line 1562, in cross_val_score
    cv = check_cv(cv, X, y, classifier=is_classifier(estimator))

  File "D:\installations\AC\lib\site-packages\sklearn\cross_validation.py", line 1823, in check_cv
    cv = StratifiedKFold(y, cv)

  File "D:\installations\AC\lib\site-packages\sklearn\cross_validation.py", line 569, in __init__
    label_test_folds = test_folds[y == label]

IndexError: too many indices for array

我尝试将 n_estimators 更改为更小的值,但它仍然显示相同的错误

根据 StratifiedKFold 迭代器的回溯和 scikit-learn 文档,似乎 StratifiedKFold 将 y 作为展平数组获取。在您的情况下,您传递大小为 (984, 1) 的数据框。你的代码部分应该是这样的:

score=cross_val_score(estimator=lr,
                      X=X_undersample.values,
                      y=y_undersample.values.ravel(),
                      cv=10,
                      scoring='accuracy')