Cartesian products in tensor flow

Is there an easy way to do a Cartesian product in Tensorflow, for example itertools.product? I want to get a combination of elements of two tensors ( aand b), in Python this is possible through itertools like list(product(a, b)). I am looking for an alternative in Tensorflow.

+4
source share
2 answers

I'm going to assume that both aand bare one-dimensional tensors.

To get the Cartesian product of two, I would use a combination of tf.expand_dimsand tf.tile:

a = tf.constant([1,2,3]) 
b = tf.constant([4,5,6,7]) 

tile_a = tf.tile(tf.expand_dims(a, 1), [1, tf.shape(b)[0]])  
tile_a = tf.expand_dims(tile_a, 2) 
tile_b = tf.tile(tf.expand_dims(b, 0), [tf.shape(a)[0], 1]) 
tile_b = tf.expand_dims(tile_b, 2) 

cartesian_product = tf.concat([tile_a, tile_b], axis=2) 

cart = tf.Session().run(cartesian_product) 

print(cart.shape) 
print(cart) 

As a result, you get a tensor len (a) * len (b ) * 2, where each combination of elements a, and bis represented in the last measurement.

+3
source

. cartesian_product , :

a: [N, L] b: [M, L], [N * M, L]

tile_a = tf.tile(tf.expand_dims(a, 1), [1, M, 1])  
tile_b = tf.tile(tf.expand_dims(b, 0), [N, 1, 1]) 

cartesian_product = tf.concat([tile_a, tile_b], axis=2)   
cartesian = tf.reshape(cartesian_product, [N*M, -1])

cart = tf.Session().run(cartesian) 

print(cart.shape)
print(cart) 
0

Source: https://habr.com/ru/post/1688784/


All Articles