如何使用Tensorflow执行笛卡尔积?

时间:2018-11-02 18:06:48

标签: python tensorflow

例如,我试图交叉堆叠两个张量

[0,1,2],[2,3]->[[0,2],[0,3],[1,2],[1,3],[2,2],[2,3]]

有人知道哪个功能可以做到吗?

1 个答案:

答案 0 :(得分:3)

我认为这可以满足您的需求:

import tensorflow as tf

a = tf.constant([0, 1, 2])
b = tf.constant([2, 3])
c = tf.stack(tf.meshgrid(a, b, indexing='ij'), axis=-1)
c = tf.reshape(c, (-1, 2))
with tf.Session() as sess:
    print(sess.run(c))

输出:

[[0 2]
 [0 3]
 [1 2]
 [1 3]
 [2 2]
 [2 3]]