2

I have two 2-D tensors and want to have Cartesian product of them. By Cartesian, I mean the concat of every row of first tensor with every row of second tensor. For example:

Input:

[[1,2,3],[4,5,6]]

and

[[7,8],[9,10]]

Output:

[[1,2,3,7,8],

[1,2,3,9,10],

[4,5,6,7,8],

[4,5,6,9,10]]

I've seen this post, but it doesn't work for this case. What is the best for it?

Thanks

user137927
  • 347
  • 3
  • 13

1 Answers1

3

Here is one way. Repeat elements a and b along the second and first dimension respectively, further reshape repeated a and then concatenate the two repeated tensors.

a_ = tf.reshape(tf.tile(a, [1, b.shape[0]]), (a.shape[0] * b.shape[0], a.shape[1]))
b_ = tf.tile(b, [a.shape[0], 1])

tf.concat([a_, b_], 1).eval()
#array([[ 1,  2,  3,  7,  8],
#       [ 1,  2,  3,  9, 10],
#       [ 4,  5,  6,  7,  8],
#       [ 4,  5,  6,  9, 10]])
Psidom
  • 209,562
  • 33
  • 339
  • 356