我有两个不同大小的张量,想要编写自定义合并函数
a = tf.constant([[1,2,3]])
b = tf.constant([[1,1,2,2,3,3]])
我想获取张量a
中每个点的点积与张量b
中两个点的点积。因此,在上面的示例中,1
中的元素a
与b
中的前两个元素相乘,依此类推。我不确定如何在Tensorflow中循环:
def customMergeFunct(x):
# not sure how to write a loop over a tensor
输出应为:
c = Lambda(customMergeFunct)([a,b])
with tf.Session() as sess:
print(c.eval())
=> [[2,8,18]]
答案 0 :(得分:2)
我不确定您为什么将其称为合并功能。您实际上不需要定义自定义函数。您可以使用简单的lambda函数执行此操作。这是我的解决方法。
import tensorflow as tf
from tensorflow.keras.layers import Lambda
import tensorflow.keras.backend as K
a = tf.constant([[1,2,3]])
b = tf.constant([[1,1,2,2,3,3]])
a_res = tf.reshape(a,[-1,1]) # make a.shape [3,1]
b_res = tf.reshape(b,[-1,2]) # make b.shape [3,2]
layer = Lambda(lambda x: K.sum(x[0]*x[1],axis=1))
res = layer([a_res,b_res])
with tf.Session() as sess:
print(res.eval())
答案 1 :(得分:1)
您可以执行以下操作:
a = tf.constant([[1,2,3]]) # Shape: (1, 3)
b = tf.constant([[1,1,2,2,3,3]]) # Shape: (1, 6)
def customMergeFunct(x):
# a_ = tf.tile(x[0], [2, 1]) # Duplicating 2 times (Original) # Update: No need of doing this as tf.multiply will use Broadcasting
b_ = tf.transpose(tf.reshape(x[1], [-1, 2])) # reshaping followed by transpose to make a shape of (2, 3) to serve the purpose + multiplication rule
return tf.reduce_sum(tf.multiply(x[0], b_), axis=0) # Element-wise multiplication followed by sum
# Using function
c = Lambda(customMergeFunct)([a,b])
# OR in a reduced form
c = Lambda(lambda x: tf.reduce_sum(tf.multiply(x[0], tf.transpose(tf.reshape(x[1], [-1, 2]))), axis=0))([a,b])
输出:
with tf.Session() as sess:
print(c.eval()) # Output: [2 8 18]
# OR in eager mode
print(c.numpy()) # Output: [2 8 18]
更新后的解决方案在计算上比原始解决方案有效,因为我们实际上不需要在x[0]
上应用图块