Scikit-Learn:timeseriessplit 中的测试大小

标签 scikit-learn

我正在使用 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/

相关文章:

python - k 个最近邻,具有准确度得分和混淆矩阵的交叉验证

machine-learning - 交叉验证分数的标准差是多少?

python - scikit SGDClassifierpartial_fit 不会增量学习。返回 “classes should include all valid labels"

python - sklearn LogisticRegression predict_proba() 在使用 sample_weight 参数时给出错误的预测

python - 获取 GBDT 模型树信息

python - xgboost 及其 sklearn 的集成 feature_importances_ 错误

python - 当转换器包含嵌入式管道时如何从 ELI5 获取功能名称

python - 如何在sklearn中使用make_scorer自定义评分函数

python - Scikit-learn 如何检查模型(例如 TfidfVectorizer)是否已经适合

python - Scikit-Learn 隔离森林 decision_function 分数的范围是多少?