实际上,我正试图在Keras和Tensorflow中建立一个LSTM模型。我的数据集有大约3200个项目,包含4个功能和3个标签。
X Shape: (3200, 4)
Y Shape: (3200, 3)
如果我需要大约5倍的步幅,那么我是否必须像这样重塑:
n_time_steps= 5
n_features = 4
X_train = X_train.reshape((-1, n_time_steps, n_features))
所以我得到了这些形状:
X Shape: (640, 5, 4)
Y Shape: (3200, 3)
我有点困惑,因为640=!3200个数据点。。。但是模型编译和拟合没有任何错误。但是acc和损失是疯狂的。当我尝试重新塑造Y_train时,Y形状:(640,5,3)
抛出
不兼容的形状:[10,3]vs.[10,5,3][[node sub(定义于:12)][Op:uuu推断_训练_函数_74818函数调用堆栈:训练_函数
这是我的模型
opt = 'adam'
model = keras.Sequential()
model.add(layers.LSTM(128, input_shape=(n_time_steps,4)))
model.add(layers.Dropout(0.2))
model.add(layers.Dense(3 ,activation="sigmoid"))
model.compile(optimizer=opt,loss=hn_multilabel_loss,metrics=['accuracy','mae'])
model.summary()
history = model.fit(X_train, Y_train,batch_size = 10, epochs=10, validation_split = 0.1)
有人知道如何创建具有5个时间步和4个功能的LSTM吗?什么是正确的输入和输出形状?
谢谢伙计们!
可以使用此函数将二维数据集转换为具有可自定义时间步数的数据集:
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