[英]Vectorizing the element-wise product of two 3 D tensors
Is there a way to vectorize the following code so that I can remove the loop entirely?有没有办法对以下代码进行矢量化,以便我可以完全删除循环?
x = tf.constant([[[1,2,3],[2,3,4]],[[1,2,3],[2,3,5]]])
t=tf.eye(x.shape[1])[:,:,None]
for i in range(x.shape[0]):
out = tf.multiply(t,x[i].numpy())
out=tf.reshape(out, shape=(out.shape[0], out.shape[-1]*out.shape[-2]))
print(out)
In short: how to multiply a 3 D tensor to each element of a 3 D tensor?简而言之:如何将 3D 张量乘以 3D 张量的每个元素? In my case: 3 D tensors are:
就我而言:3D张量是:
tf.Tensor(
[[[1.]
[0.]]
[[0.]
[1.]]], shape=(2, 2, 1), dtype=float32)
and和
tf.Tensor(
[[[1 2 3]
[2 3 4]]
[[1 2 3]
[2 3 5]]], shape=(2, 2, 3), dtype=int32)
expected output: following 2 tensors merged together with shape 2*2*6.预期输出:以下 2 个张量与形状 2*2*6 合并在一起。
tf.Tensor(
[[1. 2. 3. 0. 0. 0.]
[0. 0. 0. 2. 3. 4.]], shape=(2, 6), dtype=float32)
tf.Tensor(
[[1. 2. 3. 0. 0. 0.]
[0. 0. 0. 2. 3. 5.]], shape=(2, 6), dtype=float32)
Here is how you can get that result:以下是获得该结果的方法:
import tensorflow as tf
x = tf.constant([[[1, 2, 3], [2, 3, 4]],
[[1, 2, 3], [2, 3, 5]]], dtype=tf.float32)
t = tf.eye(tf.shape(x)[1], dtype=x.dtype)
# Add one dimension to x and one dimension to t
xt = tf.expand_dims(x, 1) * tf.expand_dims(t, 2)
# Reshape
result = tf.reshape(xt, (tf.shape(x)[0], tf.shape(x)[1], -1))
print(result.numpy())
# [[[1. 2. 3. 0. 0. 0.]
# [0. 0. 0. 2. 3. 4.]]
#
# [[1. 2. 3. 0. 0. 0.]
# [0. 0. 0. 2. 3. 5.]]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.