在张量阵列中获取对张量对象



我在TensorFlow框架中获得张量阵列的一对组合时有问题。我想要与numpy数组类似的过程: for x in list(itertools.combinations(features, 2))谁能指导我如何获得张量阵列的一对组合?非常感谢!

这不是很好(在元素数量中是二次的时间和空间),但确实会产生所需的结果:

import tensorflow as tf
def make_two_combinations(array):
    # Take the size of the array
    size = tf.shape(array)[0]
    # Make 2D grid of indices
    r = tf.range(size)
    ii, jj = tf.meshgrid(r, r, indexing='ij')
    # Take pairs of indices where the first is less or equal than the second
    m = ii <= jj
    idx = tf.stack([tf.boolean_mask(ii, m), tf.boolean_mask(jj, m)], axis=1)
    # Gather result
    return tf.gather(array, idx)
# Test
with tf.Graph().as_default(), tf.Session() as sess:
    features = tf.constant([0, 1, 2, 3, 4])
    comb = make_two_combinations(features)
    print(sess.run(comb))

输出:

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

最新更新