【问题标题】:WHy an error is generated when tuning n_estimators for RandomForestClassifier using cross_val_score?为什么使用 cross_val_score 为 RandomForestClassifier 调整 n_estimators 时会产生错误?
【发布时间】:2018-03-17 00:17:33
【问题描述】:

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

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 更改为较小的值,但仍然显示相同的错误

【问题讨论】:

    标签: python cross-validation data-science


    【解决方案1】:

    根据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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      • 2016-02-03
      • 2018-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多