I'm trying to create a custom layer in Keras that each time picks k random samples from the inputs tensor.
Something like that:
import random
class RandomKAggregator(tf.keras.layers.Layer):
    def __init__(self, **kwargs):
        super(RandomKAggregator, self).__init__(**kwargs)
        self.k = 3
    def call(self, inputs):
        return inputs[[random.randint(0, len(inputs) - 1) for _ in range(self.k)]]
The goal is to pick k samples across the first dimension. For example, if the inputs tensor's shape is [500, 32, 32, 3] it should return a tensor of shape [k, 32, 32, 3], where each call for the layer it should pick different k elements.
The above implementation returns TypeError: list indices must be integers or slices, not list.
I tried to use tf.gather and tf.gather_nd but couldn't resolve that.
- What is the right way to achieve the desired result?
- Also, would like to understand how TensorFlow handles indexing and how should I use lists of indices with tensors, say I want to pick [6,3,1,0]frommy_tensor, and whymy_tensor[[6,3,1,0]]doesn't work for me?
 
    