Tensorflow-Keras断开连接图

时间:2020-03-10 09:47:53

标签: python tensorflow keras tensorflow2.0 question-answering

Tensorflow版本:2.x

Python:3.7.4

断开连接的图:我正在尝试复制以下模型架构,但是当我尝试在Keras中绘制模型时,右侧部分似乎断开了。我已经将隐藏的矩阵HQ(用于问题)和HA(用于答案)作为注意力层的输入(我们可以在下面的摘要中看到Coattention层的输入-输入形状为(512,600)和(512,600)和Coattention矩阵CQ和CA的输出形状也相同。请帮助我了解这种断开连接。是否需要更正还是可以忽略?

最终型号:

inputs = [input_text1, input_text2]
outputs = score_oq_oa
model = Model(inputs=inputs, outputs=outputs)

model.summary()

enter image description here

预期的模型体系结构: enter image description here

模型生成的图形:为什么它在右侧断开连接?请帮助我理解。我没有在问答的双向层之后使用连接层,而是如上所述,我只是将两个双向层的输出矩阵作为关注层的输入。 enter image description here

问题已用Coattention层的代码更新,如下所示:

这里,HQ和HA是两个独立的双向层的隐藏状态矩阵/输出,如我们在模型体系结构中看到的那样。

class coattention(tf.keras.layers.Layer):

    def __init__(self):
        super(coattention, self).__init__()

    def call(self, HQ, HA):  

        L = tf.linalg.matmul(HA, HQ, transpose_a = True, transpose_b = False)
        AQ = tf.nn.softmax(L, axis = 1)
        AA = tf.nn.softmax(tf.transpose(L), axis = 1)

        CQ = tf.linalg.matmul(HA, AQ, transpose_a = False, transpose_b = False)
        CA = tf.linalg.matmul(HQ, AA, transpose_a = False, transpose_b = False)

        return CQ, CA


coattention_layer = coattention()
CQ, CA = coattention_layer(HQ, HA)
print ("Shape of Context vector of Question (CQ): ", CQ.shape)
print ("Shape of Context vector of Answer   (CA): ", CA.shape)

问题(CQ)的上下文向量的形状:(512,600)

答案(CA)的上下文向量的形状:(512,600)

1 个答案:

答案 0 :(得分:1)

因为您没有提供代码,所以我相信您忘记了调用Bidirectional_7层作为输入的coattention层。

这是示例代码

Ha = Input(shape=(1,2,3), name='Ha')
Hq = Input(shape=(1,2,3), name='Hq')

your_coattention_layer = Dense(12, name='your_coattention_layer')

# this part that I think you forgot
Ca = your_coattention_layer(Ha)
cQ = your_coattention_layer(Hq)


out1 = Dense(123, name='your_Ca_layer')(Ca)
out2 = Dense(123, name='your_Cq_later')(cQ)
M = Model(inputs=[Ha,Hq], outputs=[out1,out2])
M.summary()

from keras.utils import plot_model
plot_model(M, to_file='Example.png')

这是模型图片。

enter image description here