場景:嚴格意思上不應存在這種場景,如果存在,說明數據量太小了。舉個例子,假設僅有29條數據的情況下,使用LSTM模型,如果直接使用該函數進行歸集數據,則會造成驗證集數據的一些浪費。
1.函數介紹
可以使用此函數在序列數據上重新歸集滑動窗口數據。
keras.preprocessing.timeseries_dataset_from_array( data, targets, sequence_length, # 窗口大小 sequence_stride=1, #連續輸出序列之間的周期。對於步幅s,輸出采樣將開始索引data[i],data[i + s],data[i + 2 * s],等。 sampling_rate=1, # 序列中連續的各個時間步之間的時間間隔。對於rate r,時間步 用於創建樣本序列。 data[i], data[i + r], ... data[i + sequence_length] batch_size=128, # 每批中時間序列樣本的數量 shuffle=False, seed=None, start_index=None, end_index=None, )
2.官方案例
0-99的序列數據,以10個單位為滑動窗口數據,每次取數間隔2,下一集合數據跨越3個。
Example 1: Consider indices `[0, 1, ... 99]`. With `sequence_length=10, sampling_rate=2, sequence_stride=3`, `shuffle=False`, the dataset will yield batches of sequences composed of the following indices: ``` First sequence: [0 2 4 6 8 10 12 14 16 18] Second sequence: [3 5 7 9 11 13 15 17 19 21] Third sequence: [6 8 10 12 14 16 18 20 22 24] ... Last sequence: [78 80 82 84 86 88 90 92 94 96] ``` In this case the last 3 data points are discarded since no full sequence can be generated to include them (the next sequence would have started at index 81, and thus its last step would have gone over 99).
3.LSIM案例
(29,3)的0-28的序列。
d = {'a': [i for i in range(29)], 'b': [i for i in range(29)], 'c': [i for i in range(29)]} df = pd.DataFrame(d) df.head(5)
如果使用前3個數據集,預測下一個c列數據。訓練集為前80個數據,測試集為20個數據。構建訓練集的時候,因為c列數據足夠多,能夠完整構造數據。但是測試集中,由於要求data和targets長度需要相等,因此直接使用該函數歸並會導致測試集少past-1個數據。
step = 1 # 數據的選取步頻 train_split = 20 past = 3 # 使用前3個數據時間進行預測,時間窗口 future = 0 # 預測0個數據時點后的數據,就是下一個時點 features = pd.DataFrame(df.values) features = features.astype('float64') val_data = features.loc[train_split:] # 測試數據
# 構造驗證數據 label_start =past + future # 因為用前past個時點進行去測,所以要從第4個開始(即3) # 測試值已經再尾部了,所以要騰挪出(future+1)個來 x_val = val_data[:-(future+1)][[i for i in range(3)]].values # 由於輸入的序列長度需要一樣,所以需要補充y_val序列長度,補充傳長度為past-(future+1) y_val = val_data.iloc[label_start:][[2]] # 為了補空 for i in range(past-(future+1)): y_val.loc['n'+str(i)] = 0 dataset_val = keras.preprocessing.timeseries_dataset_from_array( x_val, y_val, sequence_length=sequence_length, sampling_rate=step, batch_size=batch_size, )
補0之后,測試數據比原來數據多past-1個,2個。
# 輸出數據 for batch in dataset_val.take(1): inputs, targets = batch print("val Input shape:", inputs.numpy().shape) print("val Target shape:", targets.numpy().shape)