【问题标题】:ValueError: Shape must be rank 3 but is rank 2. A `Concatenate` layer requires inputs with matching shapes except for the concatValueError: Shape must be rank 3 but is rank 2.“连接”层需要具有匹配形状的输入,但连接除外
【发布时间】:2021-02-08 09:56:09
【问题描述】:

我正在尝试使用 Tensorflow Functional API 来定义多输入神经网络。

这是我的代码:

from keras_self_attention import SeqSelfAttention
from tensorflow import keras
Input1 = Input(shape=(120, ),name="Input1")
Input2 = Input(shape=(10, ),name="Input2")
embedding_layer = Embedding(30,5,  input_length=120,)(Input1) 
lstm_layer = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(units=512))(embedding_layer)                  
attention=SeqSelfAttention(attention_activation='sigmoid')(lstm_layer) 
merge = concatenate([attention, Input2])                                  

但是,我收到以下错误:

ValueError: A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got inputs shapes: [(None, None, 1024), (None, 10)]. 

如果我将 Input2 的形状更改为 (None,10, ),则会收到此错误:

ValueError: Shape must be rank 3 but is rank 2 for '{{node model/concatenate/concat}} = ConcatV2[N=2, T=DT_FLOAT, Tidx=DT_INT32](model/dense/BiasAdd, model/Cast_1, model/concatenate/concat/axis)' with input shapes: [?,?,1024], [?,10], [].

如果我将 Input2 的形状更改为 (1,10, ),则会收到此错误:

ValueError: Shape must be rank 3 but is rank 2 for '{{node model/concatenate/concat}} = ConcatV2[N=2, T=DT_FLOAT, Tidx=DT_INT32](model/dense/BiasAdd, model/Cast_1, model/concatenate/concat/axis)' with input shapes: [?,?,1024], [?,10], [].

如何将注意力层的输出从 (None, None, 1024) 重塑为可以与 (None, 10) 连接的东西?

【问题讨论】:

  • 所以我认为您想将Input2 与序列中的每个元素连接起来?
  • 是的。我只有一个输入序列,我想对它应用自我关注,然后与另一个输入连接。我怎样才能做到这一点?我收到了上面解释的错误。
  • 查看tf.tile。您需要平铺Input2N 次,其中Nattention 输出中的时间步数。
  • @SusmitAgrawal 即使注意力层不起作用,我得到 IndexError: list index out of range (此错误消息与关于注意力的行有关)。知道如何设置超参数和/或一层一层地放置图层吗?

标签: python tensorflow keras deep-learning tensorflow2.0


【解决方案1】:

连接层的输入将没有匹配的维度。您可以在连接层前面添加一个重塑层来缓解这个问题。

[(None, None, 1024), (None, 10)].

这里一是三,一是二。将第一个输入重塑为 [None,1024] 或将第二个输入重塑为 [None, 1 , 10],以适合您的需要。

reshape_layer = tf.keras.layers.Reshape((1024,))(attention)
merge = concatenate([reshapelayer, Input2])

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 2022-07-16
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多