在测试和训练数据集中使用基于时间的拆分来拆分数据
Splitting data using time-based splitting in test and train datasets
我知道train_test_split
是随机拆分的,但我需要知道如何根据时间拆分它。
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
# this splits the data randomly as 67% test and 33% train
同一个数据集,67% train,33% test,如何按时间拆分?数据集有一列时间戳。
我尝试搜索类似的问题,但不确定该方法。
谁能简单解释一下?
在时间序列数据集上,数据拆分以不同的方式进行。 See this link for more info. Alternatively, you can try TimeSeriesSplit 来自 scikit-learn 包。所以主要思路是这样的,假设你有10个数据点按时间戳。现在拆分将是这样的:
Split 1 :
Train_indices : 1
Test_indices : 2
Split 2 :
Train_indices : 1, 2
Test_indices : 3
Split 3 :
Train_indices : 1, 2, 3
Test_indices : 4
Split 4 :
Train_indices : 1, 2, 3, 4
Test_indices : 5
依此类推。您可以查看上面 link 中显示的示例,以更好地了解 TimeSeriesSplit 在 sklearn
中的工作原理
更新
如果您有一个单独的时间列,您可以简单地根据该列对数据进行排序,然后如上所述应用 timeSeriesSplit 来获得拆分。
为了确保最终分割中有67%的训练数据和33%的测试数据,指定分割数如下:
no_of_split = int((len(data)-3)/3)
示例
X = np.array([[1, 2], [3, 4], [1, 2], [3, 4],[1, 2], [3, 4],[3, 4],[1, 2], [3, 4],[3, 4],[1, 2], [3, 4] ])
y = np.array([1, 2, 3, 4, 5, 6,7,8,9,10,11,12])
tscv = TimeSeriesSplit(n_splits=int((len(y)-3)/3))
for train_index, test_index in tscv.split(X):
print("TRAIN:", train_index, "TEST:", test_index)
#To get the indices
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
输出:
('TRAIN:', array([0, 1, 2]), 'TEST:', array([3, 4, 5]))
('TRAIN:', array([0, 1, 2, 3, 4, 5]), 'TEST:', array([6, 7, 8]))
('TRAIN:', array([0, 1, 2, 3, 4, 5, 6, 7, 8]), 'TEST:', array([ 9, 10, 11]))
如果您有一个简单的数据集,其中每一行都是一个观察值(例如,用于分类问题的非时间序列数据集)并且您想将其拆分为训练和测试,则此函数将拆分为训练和基于一列日期进行测试:
import pandas as pd
import numpy as np
from math import ceil
def train_test_split_sorted(X, y, test_size, dates):
"""Splits X and y into train and test sets, with test set separated by most recent dates.
Example:
--------
>>> from sklearn import datasets
# Fake dataset:
>>> gen_data = datasets.make_classification(n_samples=10000, n_features=5)
>>> dates = np.array(pd.date_range('2016-01-01', periods=10000, freq='5min'))
>>> np.random.shuffle(dates)
>>> df = pd.DataFrame(gen_data[0])
>>> df['date'] = dates
>>> df['target'] = gen_data[1]
# Separate:
>>> X_train, X_test, y_train, y_test = train_test_split_sorted(df.drop('target', axis=1), df['target'], 0.33, df['date'])
>>> print('Length train set: {}'.format(len(y_train)))
Length train set: 8000
>>> print('Length test set: {}'.format(len(y_test)))
Length test set: 2000
>>> print('Last date in train set: {}'.format(X_train['date'].max()))
Last date in train set: 2016-01-28 18:35:00
>>> print('First date in test set: {}'.format(X_test['date'].min()))
First date in test set: 2016-01-28 18:40:00
"""
n_test = ceil(test_size * len(X))
sorted_index = [x for _, x in sorted(zip(np.array(dates), np.arange(0, len(dates))), key=lambda pair: pair[0])]
train_idx = sorted_index[:-n_test]
test_idx = sorted_index[-n_test:]
if isinstance(X, (pd.Series, pd.DataFrame)):
X_train = X.iloc[train_idx]
X_test = X.iloc[test_idx]
else:
X_train = X[train_idx]
X_test = X[test_idx]
if isinstance(y, (pd.Series, pd.DataFrame)):
y_train = y.iloc[train_idx]
y_test = y.iloc[test_idx]
else:
y_train = y[train_idx]
y_test = y[test_idx]
return X_train, X_test, y_train, y_test
dates
参数实际上可以是您想要用于对数据进行排序的任何类型的数组或系列。
在您的情况下,您应该调用:X_train, X_test, y_train, y_test = train_test_split_sorted(X, y, 0.333, TimeStamp)
,其中 TimeStamp
是包含每个观察的时间戳信息的数组或列。
一个简单的方法..
首先:按时间排序数据
第二个:
import numpy as np
train_set, test_set= np.split(data, [int(.67 *len(data))])
这使得 train_set 包含前 67% 的数据,test_set 包含其余 33% 的数据。
如果您的数据已经根据时间排序,那么只需使用 shuffle=False
例如:
train, test = train_test_split(newdf, test_size=0.3, shuffle=False)
我知道train_test_split
是随机拆分的,但我需要知道如何根据时间拆分它。
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
# this splits the data randomly as 67% test and 33% train
同一个数据集,67% train,33% test,如何按时间拆分?数据集有一列时间戳。
我尝试搜索类似的问题,但不确定该方法。
谁能简单解释一下?
在时间序列数据集上,数据拆分以不同的方式进行。 See this link for more info. Alternatively, you can try TimeSeriesSplit 来自 scikit-learn 包。所以主要思路是这样的,假设你有10个数据点按时间戳。现在拆分将是这样的:
Split 1 :
Train_indices : 1
Test_indices : 2
Split 2 :
Train_indices : 1, 2
Test_indices : 3
Split 3 :
Train_indices : 1, 2, 3
Test_indices : 4
Split 4 :
Train_indices : 1, 2, 3, 4
Test_indices : 5
依此类推。您可以查看上面 link 中显示的示例,以更好地了解 TimeSeriesSplit 在 sklearn
中的工作原理更新 如果您有一个单独的时间列,您可以简单地根据该列对数据进行排序,然后如上所述应用 timeSeriesSplit 来获得拆分。
为了确保最终分割中有67%的训练数据和33%的测试数据,指定分割数如下:
no_of_split = int((len(data)-3)/3)
示例
X = np.array([[1, 2], [3, 4], [1, 2], [3, 4],[1, 2], [3, 4],[3, 4],[1, 2], [3, 4],[3, 4],[1, 2], [3, 4] ])
y = np.array([1, 2, 3, 4, 5, 6,7,8,9,10,11,12])
tscv = TimeSeriesSplit(n_splits=int((len(y)-3)/3))
for train_index, test_index in tscv.split(X):
print("TRAIN:", train_index, "TEST:", test_index)
#To get the indices
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
输出:
('TRAIN:', array([0, 1, 2]), 'TEST:', array([3, 4, 5]))
('TRAIN:', array([0, 1, 2, 3, 4, 5]), 'TEST:', array([6, 7, 8]))
('TRAIN:', array([0, 1, 2, 3, 4, 5, 6, 7, 8]), 'TEST:', array([ 9, 10, 11]))
如果您有一个简单的数据集,其中每一行都是一个观察值(例如,用于分类问题的非时间序列数据集)并且您想将其拆分为训练和测试,则此函数将拆分为训练和基于一列日期进行测试:
import pandas as pd
import numpy as np
from math import ceil
def train_test_split_sorted(X, y, test_size, dates):
"""Splits X and y into train and test sets, with test set separated by most recent dates.
Example:
--------
>>> from sklearn import datasets
# Fake dataset:
>>> gen_data = datasets.make_classification(n_samples=10000, n_features=5)
>>> dates = np.array(pd.date_range('2016-01-01', periods=10000, freq='5min'))
>>> np.random.shuffle(dates)
>>> df = pd.DataFrame(gen_data[0])
>>> df['date'] = dates
>>> df['target'] = gen_data[1]
# Separate:
>>> X_train, X_test, y_train, y_test = train_test_split_sorted(df.drop('target', axis=1), df['target'], 0.33, df['date'])
>>> print('Length train set: {}'.format(len(y_train)))
Length train set: 8000
>>> print('Length test set: {}'.format(len(y_test)))
Length test set: 2000
>>> print('Last date in train set: {}'.format(X_train['date'].max()))
Last date in train set: 2016-01-28 18:35:00
>>> print('First date in test set: {}'.format(X_test['date'].min()))
First date in test set: 2016-01-28 18:40:00
"""
n_test = ceil(test_size * len(X))
sorted_index = [x for _, x in sorted(zip(np.array(dates), np.arange(0, len(dates))), key=lambda pair: pair[0])]
train_idx = sorted_index[:-n_test]
test_idx = sorted_index[-n_test:]
if isinstance(X, (pd.Series, pd.DataFrame)):
X_train = X.iloc[train_idx]
X_test = X.iloc[test_idx]
else:
X_train = X[train_idx]
X_test = X[test_idx]
if isinstance(y, (pd.Series, pd.DataFrame)):
y_train = y.iloc[train_idx]
y_test = y.iloc[test_idx]
else:
y_train = y[train_idx]
y_test = y[test_idx]
return X_train, X_test, y_train, y_test
dates
参数实际上可以是您想要用于对数据进行排序的任何类型的数组或系列。
在您的情况下,您应该调用:X_train, X_test, y_train, y_test = train_test_split_sorted(X, y, 0.333, TimeStamp)
,其中 TimeStamp
是包含每个观察的时间戳信息的数组或列。
一个简单的方法..
首先:按时间排序数据
第二个:
import numpy as np
train_set, test_set= np.split(data, [int(.67 *len(data))])
这使得 train_set 包含前 67% 的数据,test_set 包含其余 33% 的数据。
如果您的数据已经根据时间排序,那么只需使用 shuffle=False
例如:
train, test = train_test_split(newdf, test_size=0.3, shuffle=False)