有没有简单的方法在Tensorflow中做笛卡尔积,如itertools.product?我想得到两个张量元素的组合(a
和b
),在Python中可以通过itertools得到list(product(a, b))
.我正在寻找Tensorflow的替代品.
我要在这里假定这两个a
和b
是1-d张量.
为了得到两者的笛卡尔积,我会用的组合tf.expand_dims
和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)
Run Code Online (Sandbox Code Playgroud)
你结束了一个LEN(一)*LEN(B)*2张量,其中的元件的每一个组合a
和b
在最后一维表示.
简短的解决方案,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]]]