Tensorflow-如何以批处理尺寸执行tf.gather

时间:2020-09-22 15:54:16

标签: python tensorflow

不幸的是,我不知道该问题的标题,也许有人可以更改?

如何用一种优雅的方式替换以下for循环?

#tensor.shape -> (batchsize,100)
#indices.shape -> (batchsize,100) 
liste = []
for i in range(tensor.shape[0]):
        liste.append(tf.gather(tensor[i,:], indices[i,:10]))

new_tensor = tf.stack(liste)
        

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题:

new_tensor = tf.gather(tensor, axis=-1, indices=indices[:, :10], batch_dims=1)

这里有一个最小的可复制示例:

import tensorflow as tf

# for version 1.x
#tf.enable_eager_execution()

tensor = tf.random.normal((2, 10))
indices = tf.random.uniform(shape=[2, 10], minval=0, maxval=4, dtype=tf.int32)

liste = []
for i in range(tensor.shape[0]):
        liste.append(tf.gather(tensor[i,:], indices[i,:5]))

new_tensor = tf.stack(liste)

print('tensor: ')
print(tensor)

print('new_tensor: ')
print(new_tensor)

new_tensor_v2 = tf.gather(tensor, axis=-1, indices=indices[:, :5], batch_dims=1)
print('new_tensor_v2: ')
print(new_tensor_v2)