0

I currently have code that allows one to take a combinatorial (cartesian) product across a particular axis. This is in numpy, and originated from a previous question Efficient axis-wise cartesian product of multiple 2D matrices with Numpy or TensorFlow

A = np.array([[1,2],
              [3,4]])
B = np.array([[10,20],
              [5,6]])
C = np.array([[50, 0],
              [60, 8]])
cartesian_product( [A,B,C], axis=1 )
>> np.array([[ 1*10*50, 1*10*0, 1*20*50, 1*20*0, 2*10*50, 2*10*0, 2*20*50, 2*20*0] 
             [ 3*5*60,  3*5*8,  3*6*60,  3*6*8,  4*5*60,  4*5*8,  4*6*60,  4*6*8]])

and to reiterate the solution:

L = [A,B,C]  # list of arrays
n = L[0].shape[0]
out = (L[1][:,None]*L[0][:,:,None]).reshape(n,-1)
for i in L[2:]:
    out = (i[:,None]*out[:,:,None]).reshape(n,-1)

Is there an existing method to perform this with broadcasting in tensorflow - without a for loop?

undercurrent
  • 285
  • 1
  • 2
  • 12

1 Answers1

0

Ok so I managed to find a pure tf based (partial) answer for two arrays. It's not currently generalizable like the numpy solution for M arrays, but that's for another question (perhaps a tf.while_loop). For those that are curious, the solution adapts from Evaluate all pair combinations of rows of two tensors in tensorflow

a = np.array([[0, 1, 2, 3],
              [4, 5, 6, 7],
              [4, 5, 6, 7]])

b = np.array([[0, 1],
              [2, 3],
              [2, 3]])

N = a.shape[0]

A = tf.constant(a, dtype=tf.float64)
B = tf.constant(b, dtype=tf.float64)

A_ = tf.expand_dims(A, axis=1)
B_ = tf.expand_dims(B, axis=2)
z = tf.reshape(tf.multiply(A_, B_), [N, -1])

>> tf_result
Out[1]: 
array([[  0.,   0.,   0.,   0.,   0.,   1.,   2.,   3.],
       [  8.,  10.,  12.,  14.,  12.,  15.,  18.,  21.],
       [  8.,  10.,  12.,  14.,  12.,  15.,  18.,  21.]])

Solutions for the multiple array case are welcome

undercurrent
  • 285
  • 1
  • 2
  • 12