scikit.learn中的cross_val_score错误

3 投票
3 回答
10267 浏览
提问于 2025-04-29 00:19

请查看以下地址的笔记本

LogisticRegression

这段代码,

scores = cross_val_score(LogisticRegression(), X, y, scoring='accuracy', cv=10)
print scores
print scores.mean()

在一台64位的Windows 7机器上会产生以下错误

---------------------------------------------------------------------------
 IndexError                                Traceback (most recent call last)
 <ipython-input-37-4a10affe67c7> in <module>()
 1 # evaluate the model using 10-fold cross-validation
 ----> 2 scores = cross_val_score(LogisticRegression(), X, y, scoring='accuracy', cv=10)
  3 print scores
  4 print scores.mean()

 C:\Python27\lib\site-packages\sklearn\cross_validation.pyc in    cross_val_score(estimator, X, y, scoring, cv, n_jobs, verbose, fit_params, score_func, pre_dispatch)
  1140                         allow_nans=True, allow_nd=True)
  1141 
  -> 1142     cv = _check_cv(cv, X, y, classifier=is_classifier(estimator))
  1143     scorer = check_scoring(estimator, score_func=score_func, scoring=scoring)
  1144     # We clone the estimator to make sure that all the folds are

  C:\Python27\lib\site-packages\sklearn\cross_validation.pyc in _check_cv(cv, X, y, classifier, warn_mask)
  1366         if classifier:
  1367             if type_of_target(y) in ['binary', 'multiclass']:
  -> 1368                 cv = StratifiedKFold(y, cv, indices=needs_indices)
  1369             else:
  1370                 cv = KFold(_num_samples(y), cv, indices=needs_indices)

  C:\Python27\lib\site-packages\sklearn\cross_validation.pyc in __init__(self, y, n_folds, indices, shuffle, random_state)
  428         for test_fold_idx, per_label_splits in enumerate(zip(*per_label_cvs)):
  429             for label, (_, test_split) in zip(unique_labels, per_label_splits):
--> 430                 label_test_folds = test_folds[y == label]
 431                 # the test split can be too big because we used
 432                 # KFold(max(c, self.n_folds), self.n_folds) instead of

IndexError: too many indices for array 

我使用的是scikit.learn 0.15.2,有人建议这里,这可能是Windows 7 64位机器的特定问题。

==============更新==============

我发现以下代码实际上是可以工作的

 from sklearn.cross_validation import KFold
 cv = KFold(X.shape[0], 10, shuffle=True, random_state=33)
 scores = cross_val_score(LogisticRegression(), X, y, scoring='accuracy', cv=cv)
 print scores

==============更新 2=============

似乎由于某些包的更新,我在我的机器上不再能重现这个错误。如果你在64位的Windows 7机器上遇到同样的问题,请告诉我。

暂无标签

3 个回答

0

导入这个模块,它应该就能正常工作了:

from sklearn.model_selection import cross_val_score
1

我知道这个回答来得有点晚。
但这个回答可能会帮助其他遇到同样错误的人。我在使用Python 3.6时也遇到了同样的问题。
当我把版本从3.6换成3.5时,就能正常使用这个功能了。
下面是我运行的示例:

accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1)

首先创建一个使用3.5版本的conda环境。

conda create -n py35 python=3.5  
source activate py35  

希望这能帮助你继续前进。

2

我遇到了和你一样的错误,正在寻找解决办法时看到了这个问题。

我使用的是相同的sklearn.cross_validation.cross_val_score(只是算法不同),而且我的电脑也是Windows 7,64位。

我试了你上面提到的解决方案,结果“有效”,但出现了以下警告:

C:\Users\E245713\AppData\Local\Continuum\Anaconda3\lib\site-packages\sklearn\cross_validation.py:1531: DataConversionWarning: 传入了一个列向量y,但期望的是一维数组。请将y的形状改为(n_samples, ),例如使用ravel()。 estimator.fit(X_train, y_train, **fit_params)

看完这个警告后,我意识到问题可能和'y'(我的标签列)的形状有关。警告中提到的关键词是“ravel()”。所以,我尝试了以下代码:

y_arr = pd.DataFrame.as_matrix(label)
print(y_arr)
print(y_arr.shape())

结果给了我

  [[1]
   [0]
   [1]
   .., 
   [0]
   [0]
   [1]]

  (87939, 1)

当我加上'ravel()'后:

y_arr = pd.DataFrame.as_matrix(label).ravel()
print(y_arr)
print(y_arr.shape())

它给了我:

[1 0 1 ..., 0 0 1]

(87939,)

'y_arr'的维度必须是(87939,)而不是(87939,1)。之后,我原来的cross_val_score就可以正常工作了,不需要再加Kfold的代码。

希望这对你有帮助。

撰写回答