我试图在sklearn版本0.18.1中使用TimeSeriesSplit交叉验证策略和LogisticRegression估算器.我得到一个错误说明:
cross_val_predict仅适用于分区
以下代码段显示了如何重现:
from sklearn import linear_model, neighbors from sklearn.model_selection import train_test_split, cross_val_predict, TimeSeriesSplit, KFold, cross_val_score import pandas as pd import numpy as np from datetime import date, datetime df = pd.DataFrame(data=np.random.randint(0,10,(100,5)), index=pd.date_range(start=date.today(), periods=100), columns='x1 x2 x3 x4 y'.split()) X, y = df['x1 x2 x3 x4'.split()], df['y'] score = cross_val_score(linear_model.LogisticRegression(fit_intercept=True), X, y, cv=TimeSeriesSplit(n_splits=2)) y_hat = cross_val_predict(linear_model.LogisticRegression(fit_intercept=True), X, y, cv=TimeSeriesSplit(n_splits=2), method='predict_proba')
我究竟做错了什么?
有几种方法可以传递cv
参数cross_val_score
.在这里你必须通过生成器进行拆分.例如
y = range(14) cv = TimeSeriesSplit(n_splits=2).split(y)
给了一个发电机.有了这个,您可以生成CV序列和测试索引数组.第一个看起来像这样:
print cv.next() (array([0, 1, 2, 3, 4, 5, 6, 7]), array([ 8, 9, 10, 11, 12, 13]))
您还可以将数据帧作为输入split
.
df = pd.DataFrame(data=np.random.randint(0,10,(100,5)), index=pd.date_range(start=date.today(), periods=100), columns='x1 x2 x3 x4 y'.split()) cv = TimeSeriesSplit(n_splits=2).split(df) print cv.next() (array([ 0, 1, 2, ..., 31, 32, 33]), array([34, 35, 36, ..., 64, 65, 66]))
在你的情况下,这应该工作:
score = cross_val_score(linear_model.LogisticRegression(fit_intercept=True), X, y, cv=TimeSeriesSplit(n_splits=2).split(df))
有关详细信息,请查看cross_val_score和TimeSeriesSplit.