针对 Tensorflow 中不同大小张量的自定义合并函数



我有两个不同大小的张量,想写一个自定义合并函数

a = tf.constant([[1,2,3]])
b = tf.constant([[1,1,2,2,3,3]])

我想取张量a中每个点的点积,张量b中的两个点。因此,在上面的示例中,a中的元素1乘以b中的前两个元素,依此类推。我不确定如何在张量流中进行循环:

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]]

我不确定你为什么称之为合并函数。您实际上不需要定义自定义函数。您可以使用简单的 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())

您可以执行以下操作:

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]上应用磁贴

相关内容

最新更新