如 scikit-learn 文档中所述,如何在 cv 中使用 TimeSeriesSplit

How to use TimeSeriesSplit in cv as mentioned in the documentation of scikit-learn

tss = TimeSeriesSplit(max_train_size=None, n_splits=10)
l =[]
neighb = [1,3,5,7,9,11,13,12,23,19,18]
for k in neighb:
    knn = KNeighborsClassifier(n_neighbors=k, algorithm='brute')
    sc = cross_val_score(knn, X1, y1, cv=tss, scoring='accuracy')
    l.append(sc.mean())

尝试使用10 fold TimeSeries Split,但是在cross_val_score的文档中,给出了我们需要传递一个交叉验证生成器或一个iterable。时间序列拆分成train和test数据到cv

后应该如何传递

类型错误
追溯(最近一次通话最后) 在 ()

 14 for k in neighb:

 15     knn = KNeighborsClassifier(n_neighbors=k, algorithm='brute')

---> 16 sc = cross_val_score(knn, X1, y1, cv=tss, scoring='accuracy')

 17     l.append(sc.mean())

 18 ~\Anaconda3\lib\site-packages\sklearn\cross_validation.py in cross_val_score(estimator, X, y, scoring, cv, n_jobs, verbose, fit_params, pre_dispatch)

1579 训练,测试,详细,None, 1580fit_params)

-> 1581 for train, test in cv)

1582 return np.array(分数)[:, 0]

1583

类型错误:'TimeSeriesSplit'对象不可迭代

只需将 tss 传递给 cv

scores = cross_val_score(knn, X_train, y_train, cv=tss , scoring='accuracy')

无需调用tss.split()

更新: 上述方法在 scikit-learn v0.19.1 上进行了测试。因此,请确保您拥有最新版本。我也在使用 TimeSeriesSplit from model_selection 模块。

编辑 1:

您现在正在使用这个:

tss = TimeSeriesSplit(n_splits=10).split(X_1)
kn = KNeighborsClassifier(n_neighbors=5, algorithm='brute') 
sc = cross_val_score(kn, X1, y1, cv=tss, scoring='accuracy') 

但是在您发布的问题中,您是这样做的:

tss = TimeSeriesSplit(n_splits=10)

查看它们之间的区别(split() 不存在)。我在 cross_val_score() 中使用这个 tss 而没有你在问题中发布的 split()

编辑 2:

伙计,您使用的是已弃用的 class。 目前您正在这样做:

from sklearn.cross_validation import cross_val_score

这是错误的。您应该会收到这样的警告:

DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.

注意这点,像这样使用model_selection模块:

from sklearn.model_selection import cross_val_score

那么你不会得到我的代码的错误。