在 Keras 中称量张量

Weighing a Tensor in Keras

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

这是我的问题:

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

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

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

我正在努力做到这一点:(50,) 层的每个元素都应与 (50, 49) 层中的每个 49 维向量相乘,输出为 (50, 49) 张量。

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

新答案,将 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])