我正在使用 Scikit-Learn timeseriessplit 将我的数据拆分为训练集和测试集。目前 timeSeries 数据集的第一个分割是 50%,接下来是 30%,在 25% 之后。我想要固定 10% 的数据用作测试集。
tscv = TimeSeriesSplit(n_splits=3)
for train_index, test_index in tscv.split(X):
print(train_index, test_index)
输出是:
[ 0 1 2 ..., 1067 1068 1069] [1070 1071 1072 ..., 2136 2137 2138]
[ 0 1 2 ..., 2136 2137 2138] [2139 2140 2141 ..., 3205 3206 3207]
[ 0 1 2 ..., 3205 3206 3207] [3208 3209 3210 ..., 4274 4275 4276]
我想要这样的东西:
tscv = TimeSeriesSplit(n_splits=3, test_size= = 0.1)
类似于 train_test_split
.如何只拆分 10% 的条目进行测试?
最佳答案
没有直接参数供您指定百分比。但是您可以相应地修改 n_splits 以获得所需的结果。
在 documentation it is mentioned :-
In the kth split, it returns first k folds as train set and the (k+1)th fold as test set.
现在你想要最后的 10% 作为测试,其余的作为训练。所以使用 n_splits=9。然后它会输出前 9 折作为训练,最后 1 折作为测试,在 for 循环的最后一次迭代中
因此,相应地更改您的代码:
test_size = 0.1
# This conversion is found in the source of TimeSeriesSplit
n_splits = (1//test_size)-1 # using // for integer division
tscv = TimeSeriesSplit(n_splits=n_splits)
for train_index, test_index in tscv.split(X):
print(train_index, test_index)
# Read below comments about following code
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
如果您保留 X_train、X_test 等 内 for 循环,则测试大小将保持在 0.1,但训练数据将相应更改(因为在 TimeSeries 中,只有测试索引之前的值才能用作训练)。
如果将其保留在 for 循环之外,则将只有一组训练和测试,其中 0.9 次训练和 0.1 次测试。
编辑 :
我不能说他们为什么选择 k+1 作为测试集。请看 user guide explanation here .
但是在source code ,他们使用了从 n_splits 计算的 test_size:-
n_samples = _num_samples(X)
n_splits = self.n_splits
n_folds = n_splits + 1
test_size = (n_samples // n_folds)
所以也许在下一个版本中他们可以拥有
test_size
作为参数。希望这可以帮助。如有任何疑问,请随时在此处发表评论。
关于Scikit-Learn:timeseriessplit 中的测试大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43359783/