繁体   English   中英

试图将具有相同形状的喀拉拉山中的两层连接起来,从而导致形状匹配错误

[英]trying to concatenate two layers in keras with the same shape giving error in shapes matching

我正在尝试使用keras功能api构建多输入多输出模型,并且正在遵循他们的代码,但是出现了该错误:

ValueError: Concatenate图层要求输入的形状与连续轴一致,但形状匹配。 得到了输入形状:[(无,50),(无,50,1)]

我跳过了嵌入层,这是代码:

def build_model(self):
    main_input = Input(shape=(self.seq_len, 1), name='main_input')
    print(main_input.shape)
    # seq_len = 50
    # A LSTM will transform the vector sequence into a single vector,
    # containing information about the entire sequence
    lstm_out = LSTM(self.seq_len,input_shape=(self.seq_len,1) )(main_input)
    self.auxiliary_output = Dense(1, activation='sigmoid', name='aux_output')(lstm_out)

    auxiliary_input = Input(shape=(self.seq_len,1), name='aux_input')
    print(auxiliary_input.shape)
    x = concatenate([lstm_out, auxiliary_input])

    # We stack a deep densely-connected network on top
    x = Dense(64, activation='relu')(x)
    x = Dense(64, activation='relu')(x)
    x = Dense(64, activation='relu')(x)

    # And finally we add the main logistic regression layer
    main_output = Dense(1, activation='sigmoid', name='main_output')(x)
    self.model = Model(inputs=[main_input, auxiliary_input], outputs=[main_output, auxiliary_output])
    print(self.model.summary())
    self.model.compile(optimizer='rmsprop', loss='binary_crossentropy',
              loss_weights=[1., 0.2])

尽管打印两层的形状均为(?,50,1),但在连接步骤中却遇到了该错误。 我不确切知道为什么得到这个,第一层的input_shape到底有什么错误,为什么它不能像print(main_input.shape)那样给我同样的形状,以及如何解决它?

更新:

我通过更改第二个输入层的形状找到了解决该错误的方法

auxiliary_input = Input(shape=(self.seq_len,), name='aux_input')

因此,现在它们可以顺利连接,但对我仍然不清楚为什么?

对于第二个输入,您在错误之前指定了以下内容:

input_shape = (50,1)# seq_length=50

这意味着最终形状为:

(None,50,1)

现在,当第一个输入通过LSTM ,由于您未指定return_sequences=True ,它将返回形状(batch_size, units)的张量。 您要与上述(None, 50, 1) 50,1 (None, 50)连接的(None, 50, 1)

您的错误消失了,因为您将第二个输入的输入形状更改为(50,)因此最终形状变为(None,50) ,它与LSTM输出匹配,因此平滑地串联在一起

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM