矢量化两个三维张量的元素乘积



有没有一种方法可以对下面的代码进行矢量化,这样我就可以完全删除循环了?

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)

简而言之:如何将三维张量乘以三维张量的每个元素?在我的情况下:三维张量是:

tf.Tensor(
[[[1.]
[0.]]
[[0.]
[1.]]], shape=(2, 2, 1), dtype=float32)

tf.Tensor(
[[[1 2 3]
[2 3 4]]
[[1 2 3]
[2 3 5]]], shape=(2, 2, 3), dtype=int32)

预期输出:以下两个张量合并在一起,形状为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)

以下是如何获得该结果:

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

最新更新