Pair sum in tensor flow

I have two tensors A

and B

, both from a shape [10 5]

. How to calculate a tensor of a C

shape [10 5 5]

such that C[x, i, j] = A[x, i] + B[x, j]

?

Edit: This is a summary analogue of the external product, not the external product itself.

+3


source to share


3 answers


Slightly more readable and concise than @ user1735003's answer:

A[:, :, None] + B[:, None, :]

      



(Actually the other answer was swapping axes)

+3


source


I am currently using a property log(e^x * e^y) == x+y

to perform an add from an operation matmul

:

op1 = tf.reshape(tf.exp(A), [10, -1, 1])
op2 = tf.reshape(tf.exp(B), [10, 1, -1])
C = tf.log(tf.matmul(op1, op2))

      



but I guess there will be an easier and faster way out.

0


source


You can rely on broadcasting .

op1 = tf.expand_dims(A, axis=2)
op2 = tf.expand_dims(B, axis=1)
C = tf.add(op1, op2)

      

Beware that @MaxB's solution is not equivalent to this, as operator is []

equivalent to call strided_slice

, not expand_dims

.

0


source







All Articles