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

Python 在tensorflow中,从张量沿0轴随机(子)采样k个条目,python,tensorflow,Python,Tensorflow,给定rank>=1T的张量,我想沿0轴均匀地随机抽取k条目 编辑:采样应作为延迟操作作为计算图的一部分,并且每次调用时应输出不同的随机项。 idxs = tf.range(tf.shape(inputs)[0]) ridxs = tf.random.shuffle(idxs)[:sample_num] rinput = tf.gather(inputs, ridxs) 例如,给定秩2的T: T = tf.constant( \ [[1,1,1,1,1], [2,2,2,2

给定
rank>=1
T
的张量,我想沿0轴均匀地随机抽取
k
条目

编辑:采样应作为延迟操作作为计算图的一部分,并且每次调用时应输出不同的随机项。

idxs = tf.range(tf.shape(inputs)[0])
ridxs = tf.random.shuffle(idxs)[:sample_num]
rinput = tf.gather(inputs, ridxs)
例如,给定秩
2
T

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]] \
     )
使用
k=3
,可能的输出为:

#output = \
#   [[34,34,34,34,34],
#    [6,6,6,6,6],
#    [72,72,72,72,72]]
如何在tensorflow中实现这一点?

您可以在索引数组中使用:

获取第一个
样本数
索引,并使用它们来选择输入的片段。

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

请注意,此示例来自rinput
,带有替换件。