【问题标题】:What should be Output shape of keras model layerskeras模型层的输出形状应该是什么
【发布时间】:2021-11-23 20:02:29
【问题描述】:

我对 keras 层的输出形状有点困惑。我创建了一个示例 keras 模型并显示了它的摘要。

numberOfLSTMcells=1
n_timesteps_in=129
n_features=61
inp =Input(shape=(n_timesteps_in, n_features))
lstm= LSTM(numberOfLSTMcells,return_sequences=True, return_state=False) (inp)
fc=Dense(64,activation='relu',name='hidden_layer')(lstm)
out=Dense(1,activation='sigmoid',name='last_layer')(fc)
model = Model(inputs=inp, outputs=out)

模型总结

Model: "model_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_3 (InputLayer)         [(None, 129, 61)]         0         
_________________________________________________________________
lstm_2 (LSTM)                (None, 129, 1)            252       
_________________________________________________________________
hidden_layer (Dense)         (None, 129, 64)           128       
_________________________________________________________________
last_layer (Dense)           (None, 129, 1)            65        
=================================================================
Total params: 445
Trainable params: 445
Non-trainable params: 0

我认为最后一层的形状应该是(None,64,1)。因为 hidden_​​layers 有 64 个神经元作为 last_layer 的输入

【问题讨论】:

    标签: python tensorflow keras


    【解决方案1】:

    由于您在LSTM 层中将参数return_sequences 设置为True,因此您将获得一个与输入的时间步数相同且每个时间步的输出空间为1 的序列,因此形状为(None, 129, 1)。之后,您将Dense 层应用于此张量,但此层始终应用于张量的最后一维,在您的情况下是 1 而不是 129。因此您得到输出 (None, 129, 64)。然后,您使用最终输出层,该层也应用于张量的最后一个维度,从而产生形状为(None, 129, 1) 的输出。 Tensorflow docs 也解释了这种行为:

    如果层的输入的秩大于 2,则 Dense 沿输入的 last 轴和内核的轴 0 计算输入和内核之间的点积(使用tf.tensordot)。

    如果您想使用 2D 输出 (batch_size, features) 而不是 3D (batch_size, time_steps, features),可以将 return_sequences 设置为 False,或者您可以使用 Flatten 层。

    【讨论】:

      猜你喜欢
      • 2017-12-01
      • 2019-09-11
      • 2022-10-18
      • 1970-01-01
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      • 2019-09-23
      • 1970-01-01
      相关资源
      最近更新 更多