简体   繁体   中英

Tensorflow: searching for an op supporting vector- tensor broadcasting

I am trying to achieve something like:

inputs:

  1. x: a vector with length n, [x1,x2,...,xn], elements (xi, i=1,2,...n) are scalars.
  2. T: a tensor with length n in its first dimension, [t1,t2,...tn], elements (ti, i=1,2,..,n) are tensors with rank 3.

return: a tensor, [x1*t1, x2*t2, ... xn*tn] .

I know this can be achieved by tf.stack([x[i]*T[i] for i in range(n)]) , wonder if there are any elegant approaches without iteration.

Just bring the two vectors to the same dimensions:

T = tf.constant([[[[1,1]]],[[[2,2]]]]) 
x = tf.constant([3,4])
xr = tf.reshape(x, [-1,1,1,1])
res = T*xr

Running res will print:

 [[[[3, 3]]],[[[8, 8]]]]

which is exactly what you're asking for.

Once the two tensor are of the same dimension, tf will take care of broadcasting the op (reshaping is needed to perform the broadcasting correctly)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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