Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy random choice in Tensorflow

Tags:

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.

like image 556
seleucia Avatar asked Dec 13 '16 14:12

seleucia


2 Answers

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.

like image 198
sygi Avatar answered Sep 21 '22 16:09

sygi


In tensorflow 2.0 tf.compat.v1.multinomial is deprecated instead use tf.random.categorical

like image 30
Arvind Avatar answered Sep 20 '22 16:09

Arvind