在张量流中,沿 0 轴从张量中随机(子)采样 k 个条目

syl*_*ong 2 python tensorflow

给定 的张量rank>=1 T,我想从中随机采样k条目,均匀地,沿 0 轴。

编辑:采样应该是计算图的一部分作为惰性操作,并且每次调用时都应该输出不同的随机条目。

例如,给出Trank 2

T = tf.constant( \
     [[1,1,1,1,1],
      [2,2,2,2,2],
      [3,3,3,3,3],
      ....
      [99,99,99,99,99],
      [100,100,100,100,100]] \
     )
Run Code Online (Sandbox Code Playgroud)

使用k=3,可能的输出是:

#output = \
#   [[34,34,34,34,34],
#    [6,6,6,6,6],
#    [72,72,72,72,72]]
Run Code Online (Sandbox Code Playgroud)

如何在 tensorflow 中实现这一点?

P-G*_*-Gn 6

您可以对索引数组使用随机洗牌

获取第一个sample_num索引,并使用它们来选择输入的切片。

idxs = tf.range(tf.shape(inputs)[0])
ridxs = tf.random.shuffle(idxs)[:sample_num]
rinput = tf.gather(inputs, ridxs)
Run Code Online (Sandbox Code Playgroud)