【问题标题】:How to feed only half of the RNN output to next RNN output layer in tensorflow?如何仅将一半的 RNN 输出馈送到 tensorflow 中的下一个 RNN 输出层?
【发布时间】:2023-10-17 06:43:01
【问题描述】:

我只想将奇数位置的 RNN 输出提供给下一个 RNN 层。如何在 tensorflow 中实现这一点?

我基本上想在下图中构建顶层,将序列大小减半。底层只是一个简单的RNN。

【问题讨论】:

  • 请提供您目前拥有的代码以及您期望的清晰图表。
  • @thushv89 添加了图表。我还不知道如何为顶层编写代码。底层只是一个简单的RNN层。

标签: tensorflow neural-network recurrent-neural-network


【解决方案1】:

这是你需要的吗?

from tensorflow.keras import layers, models
import tensorflow.keras.backend as K

inp = layers.Input(shape=(10, 5))
out = layers.LSTM(50, return_sequences=True)(inp)
out = layers.Lambda(lambda x: tf.stack(tf.unstack(out, axis=1)[::2], axis=1))(out)
out = layers.LSTM(50)(out)
out = layers.Dense(20)(out)
m = models.Model(inputs=inp, outputs=out)
m.summary()

您得到以下模型。你可以看到第二个 LSTM 在总共 10 个步骤中只得到了 5 个时间步(即前一层的每隔一个输出)

Model: "model_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_2 (InputLayer)         [(None, 10, 5)]           0         
_________________________________________________________________
lstm_2 (LSTM)                (None, 10, 50)            11200     
_________________________________________________________________
lambda_1 (Lambda)            (None, 5, 50)             0         
_________________________________________________________________
lstm_3 (LSTM)                (None, 50)                20200     
_________________________________________________________________
dense_1 (Dense)              (None, 20)                1020      
=================================================================
Total params: 32,420
Trainable params: 32,420
Non-trainable params: 0

【讨论】:

    最近更新 更多