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))
这不是很有效(在元素数量上是时间和空间的二次方),但它确实产生了预期的结果:
输出:
相关问题 更多 >
编程相关推荐