Cartesian Product in Tensorflow

后端 未结 4 492
醉梦人生
醉梦人生 2020-12-02 01:56

Is there any easy way to do cartesian product in Tensorflow like itertools.product? I want to get combination of elements of two tensors (a and b),

4条回答
  •  孤城傲影
    2020-12-02 02:20

    A shorter solution to the same, using tf.add() for broadcasting (tested):

    import tensorflow as tf
    
    a = tf.constant([1,2,3]) 
    b = tf.constant([4,5,6,7]) 
    
    a, b = a[ None, :, None ], b[ :, None, None ]
    cartesian_product = tf.concat( [ a + tf.zeros_like( b ),
                                     tf.zeros_like( a ) + b ], axis = 2 )
    
    with tf.Session() as sess:
        print( sess.run( cartesian_product ) )
    

    will output:

    [[[1 4]
    [2 4]
    [3 4]]

    [[1 5]
    [2 5]
    [3 5]]

    [[1 6]
    [2 6]
    [3 6]]

    [[1 7]
    [2 7]
    [3 7]]]

提交回复
热议问题