Skip to content

Instantly share code, notes, and snippets.

@sumanthratna
Last active May 25, 2020 23:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sumanthratna/b9b57134bb76c9fc62b73553728ca896 to your computer and use it in GitHub Desktop.
Save sumanthratna/b9b57134bb76c9fc62b73553728ca896 to your computer and use it in GitHub Desktop.
Randomly select a value from a Python list in TensorFlow 2.
import tensorflow as tf
my_list = ['item1', 'item2', 'item3']
index = tf.random.uniform(
[],
maxval=len(my_list),
dtype=tf.int32
)
index = tf.random.fixed_unigram_candidate_sampler(
tf.constant( # true_classes
[range(len(my_list))],
dtype=tf.int64
),
len(my_list), # num_true
1, # num_sampled
False, # unique
len(my_list), # range_max
unigrams=[1. / len(my_list)] * len(my_list)
)[0]
index = tf.random.uniform_candidate_sampler(
[range(0, len(my_list))], # true_classes
len(my_list), # num_true
1, # num_sampled,
False, # unique
len(my_list) # range_max
)[0]
# eager execution:
random_value = my_list[index.numpy().item()]
# autograph:
random_value = my_list[index]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment