Is there an equivalent function to numpy random choice in Tensorflow. In numpy we can get an item randomly from the given list with its weights.
np.random.choice([1,2,3,5], 1, p=[0.1, 0, 0.3, 0.6, 0])
This code will select an item from the given list with p weights.
No, but you can achieve the same result using tf.multinomial:
elems = tf.convert_to_tensor([1,2,3,5]) samples = tf.multinomial(tf.log([[1, 0, 0.3, 0.6]]), 1) # note log-prob elems[tf.cast(samples[0][0], tf.int32)].eval() Out: 1 elems[tf.cast(samples[0][0], tf.int32)].eval() Out: 5
The [0][0]
part is here, as multinomial
expects a row of unnormalized log-probabilities for each element of the batch and also has another dimension for the number of samples.
In tensorflow 2.0 tf.compat.v1.multinomial
is deprecated instead use tf.random.categorical
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With