Вы можете использовать эту функцию для преобразования 2D-набора данных в набор данных с настраиваемым количеством временных шагов:
def multivariate_data(dataset, target, start_index, end_index, history_size,
target_size, step, single_step=False):
data = []
labels = []
start_index = start_index + history_size
if end_index is None:
end_index = len(dataset) - target_size
for i in range(start_index, end_index):
indices = range(i-history_size, i, step)
data.append(dataset[indices])
if single_step:
labels.append(target[i+target_size])
else:
labels.append(target[i:i+target_size])
return np.array(data), np.array(labels)
Я успешно справился с вашей задачей (я немного упростил):
import tensorflow as tf
import numpy as np
from tensorflow.keras import layers
X_train = np.random.rand(3200, 4)
y_train = np.random.randint(0, 2, (3200, 3))
def multivariate_data(dataset, target, start_index, end_index, history_size,
target_size, step, single_step=False):
data, labels = [], []
start_index = start_index + history_size
if end_index is None:
end_index = len(dataset) - target_size
for i in range(start_index, end_index):
indices = range(i-history_size, i, step)
data.append(dataset[indices])
if single_step:
labels.append(target[i+target_size])
else:
labels.append(target[i:i+target_size])
return np.array(data), np.array(labels)
X_train, y_train = multivariate_data(X_train, y_train, 0, 3200, 5, 0, 1, True)
n_time_steps, n_features = 5, 4
model = tf.keras.Sequential()
model.add(layers.LSTM(128, input_shape=(n_time_steps,4)))
model.add(layers.Dense(3))
model.compile(optimizer='adam',loss='mae')
history = model.fit(X_train, y_train, batch_size = 10, epochs=1)
Вывод:
10/3195 [..............................] - ETA: 16:12 - loss: 0.3244
120/3195 [>.............................] - ETA: 1:19 - loss: 0.2725
230/3195 [=>............................] - ETA: 40s - loss: 0.2536
330/3195 [==>...........................] - ETA: 27s - loss: 0.2545
440/3195 [===>..........................] - ETA: 20s - loss: 0.2597