[英]About Output of the Keras LSTM
我已經使用Keras構建了一個LSTM體系結構。 我的目標是將長度為29的浮點數的時間序列輸入序列映射到長度為29的浮點數的輸出序列。 我正在嘗試實施“多對多”方法。 我按照這篇文章來實現這樣的模型。
首先,將每個數據點重塑為形狀為(( np.array
))的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.
ValueError: All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.
我該如何解決這個問題?
您的模型幾乎沒有缺陷。
模型的最后一層是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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.