sklearn.model_selection 'KFold' 对象不可迭代
Posted
技术标签:
【中文标题】sklearn.model_selection \'KFold\' 对象不可迭代【英文标题】:sklearn.model_selection 'KFold' object is not iterablesklearn.model_selection 'KFold' 对象不可迭代 【发布时间】:2018-04-17 20:37:41 【问题描述】:下面的代码有问题
这是代码
# simulate splitting a dataset of 25 observations into 5 folds
from sklearn.model_selection import KFold
kf = KFold(n_splits=5, random_state=None, shuffle=False)
# print the contents of each training and testing set
print(' :^61 '.format('Iteration',
'Training set observations',
'Testing set observations'))
for iteration, data in enumerate(kf, start=1):
print(':^9 !s:^25'.format(iteration, data[0], data[1]))
TypeError: 'KFold' 对象不可迭代
TypeError Traceback (most recent call last)
<ipython-input-21-13995db0f7c7> in <module>()
5 # print the contents of each training and testing set
6 print(' :^61 '.format('Iteration', 'Training set
observations', 'Testing set observations'))
----> 7 for iteration, data in enumerate(kf, start=1):
8 print(':^9 !s:^25'.format(iteration, data[0], data[1]))
TypeError: 'KFold' object is not iterable
【问题讨论】:
【参考方案1】:“cross_validation”类中有一个参数“y”(要拆分为 K 折的样本):
class sklearn.cross_validation.StratifiedKFold(y, n_folds=3, shuffle=False, random_state=None)[来源]
类model_selection这个参数对我来说不够用
# simulate splitting a dataset of 25 observations into 5 folds
from sklearn.model_selection import KFold
kf = KFold(n_splits=5, random_state=None, shuffle=False)
Vec = np.arange(0,26)
# print the contents of each training and testing set
print(' :^61 '.format('Iteration',
'Training set observations',
'Testing set observations'))
for iteration, data in enumerate(kf.split(Vec), start=1):
print(':^9 !s:^25'.format(iteration, data[0], data[1]))
【讨论】:
原始代码中唯一需要更改的是kf.split(X)
,而不仅仅是kf
。以上是关于sklearn.model_selection 'KFold' 对象不可迭代的主要内容,如果未能解决你的问题,请参考以下文章
sklearn.model_selection 无法加载 DLL
sklearn.model_selection.train_test_split 用法
sklearn.model_selection.cross_val_score的score函数公式是啥?
我无法导入 sklearn.model_selection.train_test_split