函数式API中的Keras Multiply()层

7

在新的API更改下,您如何在Keras中进行层间逐元素乘法? 在旧的API下,我会尝试像这样:

merge([dense_all, dense_att], output_shape=10, mode='mul')

我尝试了这个(MWE):
from keras.models import Model
from keras.layers import Input, Dense, Multiply

def sample_model():
        model_in = Input(shape=(10,))
        dense_all = Dense(10,)(model_in)
        dense_att = Dense(10, activation='softmax')(model_in)
        att_mull = Multiply([dense_all, dense_att]) #merge([dense_all, dense_att], output_shape=10, mode='mul')
        model_out = Dense(10, activation="sigmoid")(att_mull)
        return 0

if __name__ == '__main__':
        sample_model()

完整的跟踪信息:

Using TensorFlow backend.
Traceback (most recent call last):
  File "testJan17.py", line 13, in <module>
    sample_model()
  File "testJan17.py", line 8, in sample_model
    att_mull = Multiply([dense_all, dense_att]) #merge([dense_all, dense_att], output_shape=10, mode='mul')
TypeError: __init__() takes exactly 1 argument (2 given)

编辑:

我尝试实现tensorflow的逐元素乘法函数。当然,结果不是Layer()实例,所以它不能工作。以下是为了纪念而尝试的代码:

def new_multiply(inputs): #assume two only - bad practice, but for illustration...
        return tf.multiply(inputs[0], inputs[1])


def sample_model():
        model_in = Input(shape=(10,))
        dense_all = Dense(10,)(model_in)
        dense_att = Dense(10, activation='softmax')(model_in) #which interactions are important?
        new_mult = new_multiply([dense_all, dense_att])
        model_out = Dense(10, activation="sigmoid")(new_mult)
        model = Model(inputs=model_in, outputs=model_out)
        model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
        return model
3个回答

14

使用keras版本>2.0:

from keras.layers import multiply
output = multiply([dense_all, dense_att])

...嗯。好吧,我猜Multiply()是multiply()的一个封装或者类似的东西。谢谢! - StatsSorceress
@StatsSorceress 正好相反:multiply()Multiply()的包装器。 - Alexey Romanov

6
在函数式API中,您只需要使用`multiply`函数,注意小写字母"m"。`Multiply`类是一个层,旨在与顺序API一起使用。
更多信息请参见https://keras.io/layers/merge/#multiply_1

哈!差不多同时 :) - Marcin Możejko

5
您需要在前面再加一个括号。
from keras.layers import Multiply
att_mull = Multiply()([dense_all, dense_att])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接