首页 文章

Scikit train_test_split by a indice

提问于
浏览
1

我有一个按日期索引的 pandas 数据框 . 让's assume it from Jan-1 to Jan-30. I want to split this dataset into X_train, X_test, y_train, y_test but I don' t想要混合日期,所以我希望火车和测试样本除以某个日期(或索引) . 我尝试着

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次测试)

我怎样才能做到这一点?谢谢

2 回答

  • 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]
    
  • 1

    你应该使用

    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

相关问题