Tensorflow:逐行迭代张量并执行元素乘法

问题描述 投票:1回答:1

我有两个张量,

x = shape(batchsize, 29, 64), 
y = shape(batchsize, 29, 29, 64)

我想在y上逐行迭代并使用x执行元素乘法,结果应该是一个形状(批量大小,29,64)。

我将如何顺序编程:

for batchnr in range(x.shape[0]): 
    for elem in y[batchnr]:
        x[batchnr] = tf.multiply(x[batchnr], elem)

我使用tf.scan,tf.map_fn,tf.while_loop尝试了几件事。但是,我无法弄清楚如何正确而有效地做到这一点。

python tensorflow matrix-multiplication
1个回答
2
投票

如果我理解你的问题,你希望,对于批处理中的每个例子,在y[batchnr],元素方面,然后用x,也是元素方式的29个形状矩阵(29,64)的乘法。如果这是正确的,那么我认为你可以使用tf.reduce_prod()

例如,

# x = shape(batchsize, 29, 64), 
# y = shape(batchsize, 29, 29, 64)
# ...

z = tf.reduce_prod(y, axis=1)  # shape(batchsize, 29, 64), product of 29 matrices element-wise
r = tf.multiply(x, z)  # shape(batchsize, 29, 64)
© www.soinside.com 2019 - 2024. All rights reserved.