Tensorflow中的笛卡尔积

Jab*_*aba 7 python tensorflow

有没有简单的方法在Tensorflow中做笛卡尔积,如itertools.product?我想得到两个张量元素的组合(ab),在Python中可以通过itertools得到list(product(a, b)).我正在寻找Tensorflow的替代品.

Sun*_*eef 7

我要在这里假定这两个ab是1-d张量.

为了得到两者的笛卡尔积,我会用的组合tf.expand_dimstf.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) 
Run Code Online (Sandbox Code Playgroud)

你结束了一个LEN(一)*LEN(B)*2张量,其中的元件的每一个组合ab在最后一维表示.


Pet*_*dan 6

简短的解决方案,tf.add()用于广播(已测试):

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 ) )
Run Code Online (Sandbox Code Playgroud)

将输出:

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

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

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

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

  • 这个答案太棒了!虽然可能不太可读,但它更具普遍性。似乎适用于维度 1 之后任意维度的张量。例如,它仍然返回您对 `a = tf.constant([[[1,2,3],[4,5,6]],[[ 1,1,1],[1,1,1]]])``b = tf.constant([[[[7,8,9],[10,11,12]]])` (2认同)