【问题标题】:How to Concatenate 2 Embedding layers with 'mask_zero=True' in Keras2.0?如何在 Keras2.0 中使用 'mask_zero=True' 连接 2 个嵌入层?
【发布时间】:2018-10-14 10:32:30
【问题描述】:

我有两个嵌入层,一个分配了mask_zero=True,另一个没有,定义如下。

a = Input(shape=[30])
b = Input(shape=[30])
emb_a = Embedding(10, 5, mask_zero=True)(a)
emb_b = Embedding(20, 5, mask_zero=False)(b)
cat = Concatenate(axis=1)([emb_a, emb_b]) # problem here
model = Model(inputs=[a, b], outputs=[cat])

当我尝试将它们连接到 axis=1 时,我期望输出大小为 [None, 60, 5],但它引发了错误:

ValueError: Dimension 0 in both shapes must be equal, but are 1 and 5.
Shapes are [1] and [5]. for 'concatenate_1/concat_1' (op: 'ConcatV2') with input shapes: 
[?,30,1], [?,30,5], [] and with computed input tensors: input[2] = <1>.

为什么emb_a的形状变成[None, 30, 1]?为什么还有一个空张量[]被输入到Concatenate中?

如果两个嵌入层都分配mask_zero=True 或都分配mask_zero=False,则不会引发此错误。 如果它们在axis=2 处连接,也不会引发此错误。

我的keras版本是2.0.8。

谢谢。

【问题讨论】:

    标签: python keras embedding masking


    【解决方案1】:

    因为您在一种情况下有mask_zero=True 而在另一种情况下有mask_zero=False 在内部导致一些问题(这不应该发生),也许这是一个错误,您可以在 Github 上报告。

    目前,我认为有效的 2 个选项是仅将其中一个用于两个嵌入:mask_zero=Truemask_zero=False

    a = Input(shape=[30])
    b = Input(shape=[30])
    emb_a = Embedding(10, 5)(a)
    emb_b = Embedding(20, 5)(b)
    cat = Concatenate(axis=1)([emb_a, emb_b])
    model = Model(inputs=[a, b], outputs=[cat])
    
    print(model.output_shape) # (None, 60, 5)
    

    解决此问题的另一种方法是连接axis=-1

    a = Input(shape=[30])
    b = Input(shape=[30])
    emb_a = Embedding(10, 5, mask_zero=True)(a)
    emb_b = Embedding(20, 5, mask_zero=False)(b)
    cat = Concatenate()([emb_a, emb_b]) # problem here
    model = Model(inputs=[a, b], outputs=[cat])
    
    print(model.output_shape) # (None, 30, 10)
    

    【讨论】:

    • 我真的需要在axis=1处连接两个嵌入,因为输入ab可能有不同的词(例如a 15个词和b 30个词),而嵌入剩下5个。我想将(None, 15, 5)(None, 30, 5) 连接成(None, 45, 5)
    • @GeraltXu 我仔细研究了一下,觉得 Keras 有 bug,建议你报告。暂时我已经添加了我发现有效的其他选项。
    猜你喜欢
    • 2018-10-02
    • 2020-02-12
    • 2019-11-23
    • 2019-09-07
    • 2018-10-20
    • 2018-01-18
    • 2020-05-29
    • 2019-01-15
    • 2018-05-09
    相关资源
    最近更新 更多