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

Python 两个三维张量的元素乘积矢量化,python,tensorflow,Python,Tensorflow,有没有办法将下面的代码矢量化,这样我就可以完全删除循环 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[-

有没有办法将下面的代码矢量化,这样我就可以完全删除循环

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)

预期输出:以下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)

以下是如何获得该结果:

将tensorflow导入为tf
x=tf.常数([[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)
#将一个维度添加到x,将一个维度添加到t
xt=tf.展开尺寸(x,1)*tf.展开尺寸(t,2)
#重塑
结果=tf.重塑(xt,(tf.形状(x)[0],tf.形状(x)[1],-1))
打印(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.]]]

以下是获得该结果的方法:

将tensorflow导入为tf
x=tf.常数([[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)
#将一个维度添加到x,将一个维度添加到t
xt=tf.展开尺寸(x,1)*tf.展开尺寸(t,2)
#重塑
结果=tf.重塑(xt,(tf.形状(x)[0],tf.形状(x)[1],-1))
打印(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.]]]

sol。看起来似乎有道理,但有一个陷阱。当我们在自定义层(如
sequence\u length
batch\u size
)中使用形状时,Keras/tf会引发编译时错误。具体地说,执行x.shape[0]要求的批量大小是
None
(其动态批量大小)。所以编译器产生了错误。@chandresh我在解决方案中使用了
tf.shape(x)[0]
,而不是
x.shape[0]
,不是吗?
tf.shape(x)[0]
将尝试获取
批量大小
。不管怎样,我为第一个参数(
batch\u size
)提供了
-1
,并将其他参数作为参数传递,它正在工作。谢谢,索尔。看起来似乎有道理,但有一个陷阱。当我们在自定义层(如
sequence\u length
batch\u size
)中使用形状时,Keras/tf会引发编译时错误。具体地说,执行x.shape[0]要求的批量大小是
None
(其动态批量大小)。所以编译器产生了错误。@chandresh我在解决方案中使用了
tf.shape(x)[0]
,而不是
x.shape[0]
,不是吗?
tf.shape(x)[0]
将尝试获取
批量大小
。不管怎样,我为第一个参数(
batch\u size
)提供了
-1
,并将其他参数作为参数传递,它正在工作。谢谢
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)