我使用Keras构建了一个LSTM架构。我的目标是将长度为29的浮点数的时间序列输入序列映射到长度为29的浮点数的输出序列。我正在尝试实施“多对多”方法。我遵循this post来实现这种模型。
我首先将每个数据点重塑为形状为((1、29、1)的np.array
。我有多个数据点,并分别在每个模型上训练模型。以下代码是我建立模型的方式:
def build_model():
# define model
model = tf.keras.Sequential()
model.add(tf.keras.layers.LSTM(29, return_sequences=True, input_shape=(29, 1)))
model.add(tf.keras.layers.LeakyReLU(alpha=0.3))
model.compile(optimizer='sgd', loss='mse', metrics = ['mae'])
#cast data
for point in train_dict:
train_data = train_dict[point]
train_dataset = tf.data.Dataset.from_tensor_slices((
tf.cast(train_data[0], features_type),
tf.cast(train_data[1], target_type))
).repeat() #cast into X, Y
# fit model
model.fit(train_dataset, epochs=100,steps_per_epoch = 1,verbose=0)
print(model.summary())
return model
我很困惑,因为当我调用model.predict(test_point, steps = 1, verbose = 1)
时模型返回29个长度为29的序列!根据我对链接帖子的了解,我不知道为什么会这样。当我尝试使用return_state=True
而不是return_sequences=True
时,我的代码将引发以下错误:ValueError: All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.
我该如何解决问题?
答案 0 :(得分:1)
您的模型几乎没有缺陷。
模型的最后一层是LSTM。假设您要进行分类/回归。这之后应该是密集层(SoftMax / Sigmoid-分类,线性-回归)。但是由于这是一个时间序列问题,因此应将密集层包裹在TimeDistributed包装器中。
在LSTM之上应用LeakyReLU很奇怪。
我已修复上述问题的代码。看看是否有帮助。
from tensorflow.keras.layers import Embedding, Input, Bidirectional, LSTM, Dense, Concatenate, LeakyReLU, TimeDistributed
from tensorflow.keras.initializers import Constant
from tensorflow.keras.models import Model
from tensorflow.keras.models import Sequential
def build_model():
# define model
model = Sequential()
model.add(LSTM(29, return_sequences=True, input_shape=(29, 1)))
model.add(TimeDistributed(Dense(1)))
model.compile(optimizer='sgd', loss='mse', metrics = ['mae'])
print(model.summary())
return model
model = build_model()