【问题标题】:Weighing a Tensor in Keras在 Keras 中称量张量
【发布时间】:2017-06-21 16:28:01
【问题描述】:

我有一个非常简单的问题,似乎在 Keras 中没有内置解决方案。

这是我的问题:

我有一个 (50,) 维张量(第 1 层的输出),它应该乘以一个 (50, 49) 维张量。

这些张量是某些层的输出。

我认为简单的 multiply([layer1, layer2]) 会起作用,但事实证明它们需要张量具有相同的形状。

我试图得到这个:(50,) 层的每个元素都应该乘以 (50, 49) 层中的每个 49 维向量,将输出作为 (50, 49) 张量。

有什么方法可以在 Keras 中完成?

【问题讨论】:

    标签: machine-learning deep-learning keras keras-layer keras-2


    【解决方案1】:

    新答案,将 layer2 视为 (50,49)

    在这里,您需要对 layer2 中的每一行进行标量乘法。然后我们将考虑将“50”作为批次的一部分,并将形状 (1,1) 与形状 (49,1) 相乘。为了在 batch_dot 中保持 50 的独立性,我们将使用 -1 作为通配符重塑 lambda 函数内部的内容:

    out = Lambda(myMultiplication, output_shape=(50,49))([layer1,layer2])
    

    在哪里

    import keras.backend as K
    
    def myMultiplication(x):
        
        #inside lambda functions, there is an aditional axis, the batch axis. Normally, we use -1 for this dimension. We can take advantage of it and simply hide the unwanted 50 inside this -1. 
    
        L1 = K.reshape(x[0], (-1,1,1))
        L2 = K.reshape(x[1], (-1,49,1))
    
        result = K.batch_dot(L1,L2, axes=[1,2])
    
        #here, we bring the 50 out again, keeping the batch dimension as it was originally   
        return K.reshape(result,(-1,50,49))
    

    旧答案,当我认为 layer2 是 (49,) 而不是 (50,49) 时

    您需要一个带有 batch_dot 的 lambda 层(用于自定义函数)。

    批处理点是实际的矩阵乘法,而乘法是元素乘法。为此,您应该将向量重塑为矩阵,将其中之一转置以实现您想要的乘法。

    所以:

    layer1 = Reshape((1,50))(layer1)
    layer2 = Reshape((49,1))(layer2)
    out = Lambda(myMultiplication, output_shape=(50,49))([layer1,layer2])
    

    在哪里

    import keras.backend as K
    
    def myMultiplication(x):
        return K.batch_dot(x[0],x[1],axes=[1,2])
    

    【讨论】:

    • 感谢您的回答。我得到 ValueError: total size of new array must be changed on line layer2=Reshape... : layer 2 is sized (50, 49)..你能建议如何解决这个问题吗?非常感谢。
    • 啊,我想你刚刚(49,)。查看新答案:)
    • 非常感谢您的回答和解释!
    猜你喜欢
    • 1970-01-01
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多