简体   繁体   中英

In tensorflow, randomly (sub)sample k entries from a tensor along 0-axis

Given a tensor of rank>=1 T , I would like to randomly sample k entries from it, uniformly, along the 0-axis.

EDIT: The sampling should be part of the computation graph as a lazy operation and should output different random entries every time it is called.

For instance, given T of rank 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]] \
     )

With k=3 , a possible output would be:

#output = \
#   [[34,34,34,34,34],
#    [6,6,6,6,6],
#    [72,72,72,72,72]]

How can this be achieved in tensorflow?

You can use a random shuffle on an array of indices:

Take the first sample_num indices, and use them to pick slices of your input.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM