获取张量数组中的成对张量对象

2024-04-25 15:29:07 发布

您现在位置:Python中文网/ 问答频道 /正文

在Tensorflow框架中获取张量数组的成对组合时,我遇到了一个问题。 我希望处理过程与numpy数组类似: for x in list(itertools.combinations(features, 2)) 有谁能教我如何得到张量阵的一对组合? 非常感谢你!你知道吗


Tags: innumpy框架fortensorflow数组listfeatures
1条回答
网友
1楼 · 发布于 2024-04-25 15:29:07

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

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]]

相关问题 更多 >