Tensorflow 中的笛卡尔积 [英] Cartesian Product in Tensorflow
问题描述
有没有像 itertools.product 那样在 Tensorflow 中做笛卡尔积的简单方法?我想获得两个张量元素的组合(a
和 b
),在 Python 中可以通过 itertools 作为 list(product(a, b))代码>.我正在 Tensorflow 中寻找替代方案.
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
), in Python it is possible via itertools as list(product(a, b))
. I am looking for an alternative in Tensorflow.
推荐答案
这里我将假设 a
和 b
都是一维张量.
I'm going to assume here that both a
and b
are 1-D tensors.
要获得两者的笛卡尔积,我将使用 tf.expand_dims
和 tf.tile
的组合:
To get the cartesian product of the two, I would use a combination of tf.expand_dims
and 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)
你最终得到一个 len(a) * len(b) * 2 张量,其中 a
和 b
元素的每个组合在最后一个维度中表示.
You end up with a len(a) * len(b) * 2 tensor where each combination of the elements of a
and b
is represented in the last dimension.
这篇关于Tensorflow 中的笛卡尔积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!