簡體   English   中英

向量化兩個 3D 張量的元素乘積

[英]Vectorizing the element-wise product of two 3 D tensors

有沒有辦法對以下代碼進行矢量化,以便我可以完全刪除循環?

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)

簡而言之:如何將 3D 張量乘以 3D 張量的每個元素? 就我而言:3D張量是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM