首页 > 解决方案 > 如何在 LSTM 自动编码器中计算带有零填充的输入的 softmax

问题描述

我正在实现一个带有输入 x 的 LSTM 自动编码器,并希望得到与 x 相同的输出。但是,我在实施中有几个问题,请参阅下面的代码:

dict_size = 10
max_sentence_length = 5
embed_dim = 20

x = Input(shape=(max_sentence_length,), dtype='int32')
encoder_input = Embedding(dict_size, embed_dim)(x)
encoder_output=LSTM(32, return_sequences=True)(encoder_input)
deocder_output = LSTM(32, return_sequences=True)(encoder_output)
y = Dense(dict_size, activation='softmax')(deocder_output)

model = Model(inputs=x, outputs=y)
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
print(model.summary())

train_x = np.array([[3, 1, 2]])
train_x = pad_sequences(train_x, max_sentence_length, padding='post')
train_y = np_utils.to_categorical(train_x, dict_size)

model.fit(train_x, train_y, batch_size=1, epochs=1)
predict_y = model.predict(train_x)
print(predict_y)

在这段代码中,第一个问题是:“ValueError: Error when checks target: expected dense_1 to have 3 dimensions, but got array with shape (5, 10)”,我真的不知道如何先解决这个问题。

第二个问题是,x 的长度是 3,而加上额外的填充,它的长度变成了 5;在最后阶段,输出将是一个 5x10 矩阵,即最终输出的最后两个元素不应参与 softmax 的计算。有什么办法可以快速解决这个问题吗?

非常感谢!

标签: keraslstm

解决方案


推荐阅读