Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensor multiply along axis in tensorflow

The problem I have using tensorflow is as follows:

For two tensors

[[x11,x12...],[x21,x22...],...[xn1,xn2...]]

and

[y1,y2,...yn],

I want to multiply them along axis 0 to get

[[x11*y1,x12*y1...],[x21*y2,x22*y2...]...]

For example, for [[1,2],[3,4]] and [1,2], I want to get the result tensor [[1,2],[6,8]].

The real scenario is that I have two tensors A and B shaped (batches,height,width,n_channels) and (batches,1). Both are tensors defined in tensorflow. For each image of A in the batch I want to multiply it with the corresponding value in B.

like image 612
HAMMERMASH Avatar asked Feb 27 '26 18:02

HAMMERMASH


1 Answers

Given a 2-dimensional tensor x and a vector y, you just need to do:

result = x * tf.expand_dims(y, axis=-1)

Or, if you like it more:

result = x * y[:, tf.newaxis]
like image 140
jdehesa Avatar answered Mar 01 '26 07:03

jdehesa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!