Stoney
Stoney

Reputation: 407

tensorflow - map_fn to do computation on every possible combination of two tensors

does anyone know how to use map_fn or any other tensorflow-func to do a computation on every combination of two input-tensors?

So what i want is something like this: Having two arrays ([1,2] and [4,5]) i want as a result a matrix with the output of the computation (e.g. add) on every possible combination of the two arrays. So the result would be:

[[5,6],
 [6,7]]

I used map_fn but this only takes the elements index-wise:

[[5]
 [7]]

Has anyone an idea how implement this?

Thanks

Upvotes: 1

Views: 227

Answers (1)

Allen Lavoie
Allen Lavoie

Reputation: 5808

You can add new unit dimensions to each Tensor, then rely on broadcasting addition:

import tensorflow as tf
import tensorflow.contrib.eager as tfe
tfe.enable_eager_execution()
first = tf.constant([1, 2])
second = tf.constant([4, 5])
print(first[None, :] + second[:, None])

Prints:

tf.Tensor(
[[5 6]
 [6 7]], shape=(2, 2), dtype=int32)

Upvotes: 2

Related Questions