【问题标题】:what happens when you merge branches in keras with different shapes?当你在 keras 中合并不同形状的分支时会发生什么?
【发布时间】:2019-10-05 03:07:41
【问题描述】:

以下是部分代码。我试图了解“添加”的作用。为什么在这里添加两个不同形状的输入时,Add layer (None, 38, 300)的输出是?

以下是 Keras 中的代码。

image_model = Input(shape=(2048,))
x = Dense(units=EMBEDDING_DIM, activation="relu")(image_model)
x = BatchNormalization()(x)

language_model = Input(shape=(MAX_CAPTION_SIZE,))
y = Embedding(input_dim=VOCABULARY_SIZE, output_dim=EMBEDDING_DIM)(language_model)
y = Dropout(0.5)(y)

merged = add([x, y])
merged = LSTM(256, return_sequences=False)(merged)
merged = Dense(units=VOCABULARY_SIZE)(merged)
merged = Activation("softmax")(merged)

【问题讨论】:

    标签: keras-2


    【解决方案1】:

    为什么添加两个输入时Add layer的输出是(None, 38, 300) 这里有不同的形状?

    这是一种称为广播的技术。您可以在此处找到更多详细信息:https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html

    在下面的示例中,第一个输入 (16,) 沿第二个输入 (2,16) 的第二个维度 (2,) 广播,因此可以进行元素相加。

    import keras
    import numpy as np
    
    input1 = keras.layers.Input(shape=(16,))
    input2 = keras.layers.Input(shape=(2,16))
    added = keras.layers.Add()([input1, input2])
    model = keras.models.Model(inputs=[input1, input2], outputs=added)
    output = model.predict([np.ones((1,16)), np.ones((1,2,16))])
    print(output.shape)
    print(output)
    

    (1, 2, 16)

    [[[2。 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2.] [2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2.]]]

    【讨论】:

    • 感谢您的示例 - 这真的很有帮助。
    猜你喜欢
    • 2021-10-18
    • 2018-03-28
    • 1970-01-01
    • 2017-02-12
    • 1970-01-01
    • 2019-01-01
    • 2017-11-28
    • 2018-05-01
    • 1970-01-01
    相关资源
    最近更新 更多