在Tensor Array中获取对张量对象

问题描述 投票:1回答:1

在Tensorflow框架中获取Tensor数组的一对组合时遇到问题。我想要与numpy数组类似的过程:for x in list(itertools.combinations(features, 2))任何人都可以指导我如何获得张量阵列的一对组合?非常感谢你!

python numpy tensorflow itertools
1个回答
0
投票

这不是非常有效(它是元素数量的二次时间和空间),但它确实产生了预期的结果:

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]]
© www.soinside.com 2019 - 2024. All rights reserved.