Tensorflow:如何使用tensorflow操作从给定的字符串列表中选择一个随机字符串



我有一个字符串列表,如下所示,我想做张量流操作。 我想从list_2中随机选择一个字符串,用于list_1中的给定输入字符串。

我的函数看起来像这样;

list_1 = ['hello', 'how are you?', 'this is just a test']
list_2 = ['helloooo', 'thanks', 'okay']
def test(string):
if string in list_1:
print("list: ", random.choice(list_2)) 
test("hello") 

我如何使用tensorflow实现这一点?因为我在tensorflow中找不到任何tf.random.choice的东西。

这是一种基于Tensorflow Ops的不同方法:

import tensorflow as tf
list_2 = ['helloooo', 'thanks', 'okay']
len_list = tf.size(list_2)
rand_var = tf.random_uniform([1],0,len_list, dtype=tf.int32)
output = tf.gather(list_2,rand_var[0])
with tf.Session() as sess:
print(sess.run(output))

最新更新