称重在Keras的张量

时间:2017-06-21 16:28:01

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

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

下面'我的问题:

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

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

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

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

任何方式都可以在Keras完成?

1 个答案:

答案 0 :(得分: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])