简体   繁体   English

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

[英]Tensorflow: Iterate tensor row-wise and perform elementwise multiplication

I've got two tensors, 我有两个张量

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

I want to iterate row-wise over y and perform an elementwise multiplication with x, the result should be of a shape (batch size, 29, 64). 我想在y上逐行进行迭代,并与x进行元素逐次乘法,结果应为某种形状(批量大小为29、64)。

How I would program it sequentially: 我如何依次编程:

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

I tried several things using tf.scan, tf.map_fn, tf.while_loop. 我使用tf.scan,tf.map_fn,tf.while_loop尝试了几件事。 However, I can't figure out how to do it right and efficient. 但是,我不知道如何正确有效地做到这一点。

If I understand your question properly, you would like to, for each example in a batch, do the multiplication of 29 matrices of shape (29, 64) in y[batchnr] , element-wise, then with x, also element-wise. 如果我正确理解了您的问题,那么对于一个批次中的每个示例,您都希望分别在y[batchnr] 29个形状为( y[batchnr] )的矩阵分别乘以y[batchnr] ,然后分别乘以x 。 If that is correct, then I think you can use tf.reduce_prod() . 如果正确,那么我认为您可以使用tf.reduce_prod()

For example, 例如,

# 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM