在Tensorflow框架中获取Tensor数组的配对组合时遇到问题。
我想要与numpy array类似的过程:
for x in list(itertools.combinations(features, 2))
谁能指导我如何获得张量阵列的成对组合?
非常感谢你!
答案 0 :(得分: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]]