【问题标题】:Scikit train_test_split by an indiceScikit train_test_split 按索引
【发布时间】:2019-05-07 23:46:13
【问题描述】:

我有一个按日期索引的pandas 数据框。让我们假设它从 1 月 1 日到 1 月 30 日。我想将此数据集拆分为 X_train、X_test、y_train、y_test,但我不想混合日期,因此我希望将训练和测试样本除以某个日期(或索引)。我在努力

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

但是当我检查这些值时,我发现日期是混合的。我想将我的数据拆分为:

Jan-1 to Jan-24 用于训练,Jan-25 to Jan-30 用于测试(因为 test_size 为 0.2,即 24 用于训练,6 用于测试)

我该怎么做?谢谢

【问题讨论】:

  • 你应该阅读document
  • 如果你想要前 24 名,则使用x.head(24),最后 6 名使用x.tail(6) 不需要train_test split
  • @Nihal random_state=None 不起作用。试过了..
  • random_state=None 会占用numpy.random 这就是为什么它不起作用
  • 您在寻找 TimeSeriesSplit 吗? scikit-learn.org/stable/modules/generated/…

标签: python pandas scikit-learn scipy classification


【解决方案1】:

尝试使用TimeSeriesSplit

X = pd.DataFrame({'input_1': ['a', 'b', 'c', 'd', 'e', 'f'],
                  'input_2': [1, 2, 3, 4, 5, 6]},
                 index=[pd.datetime(2018, 1, 1),
                        pd.datetime(2018, 1, 2),
                        pd.datetime(2018, 1, 3),
                        pd.datetime(2018, 1, 4),
                        pd.datetime(2018, 1, 5),
                        pd.datetime(2018, 1, 6)])
y = np.array([1, 0, 1, 0, 1, 0])

这导致X 存在

           input_1  input_2
2018-01-01       a        1
2018-01-02       b        2
2018-01-03       c        3
2018-01-04       d        4
2018-01-05       e        5
2018-01-06       f        6
tscv = TimeSeriesSplit(n_splits=3)
for train_ix, test_ix in tscv.split(X):
    print(train_ix, test_ix)
[0 1 2] [3]
[0 1 2 3] [4]
[0 1 2 3 4] [5]

【讨论】:

  • 谢谢,但这不是我想要的。 @Nihal 回答了我的问题,它使用的是 shuffle=False
【解决方案2】:

你应该使用

X_train, X_test, y_train, y_test = train_test_split(X,Y, shuffle=False, test_size=0.2, stratify=None)

不要使用random_state=None,它会使用numpy.random

here 中提到使用shuffle=Falsestratify=None

【讨论】:

    猜你喜欢
    • 2020-07-14
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 2015-07-14
    • 2023-03-06
    • 2018-05-18
    相关资源
    最近更新 更多