用numpy.random.choice添加一些随机性
问题描述:
我是python和Numpy中的新手。用numpy.random.choice添加一些随机性
我有一些随机性添加到下面的代码:
def pick_word(probabilities, int_to_vocab):
"""
Pick the next word in the generated text
:param probabilities: Probabilites of the next word
:param int_to_vocab: Dictionary of word ids as the keys and words as the values
:return: String of the predicted word
"""
return int_to_vocab[np.argmax(probabilities)]
我测试了这一点:
int_to_vocab[np.random.choice(probabilities)]
但它不工作。
我也在互联网上,我还没有发现任何与我的问题有关的事情,而Numpy对我来说非常困惑。
如何在此处使用np.random.choice
?
样品情况下:
284 test_int_to_vocab = {word_i: word for word_i, word in enumerate(['this', 'is', 'a', 'test'])}
285
--> 286 pred_word = pick_word(test_probabilities, test_int_to_vocab)
287
288 # Check type
<ipython-input-6-2aff0e70ab48> in pick_word(probabilities, int_to_vocab)
6 :return: String of the predicted word
7 """
----> 8 return int_to_vocab[np.random.choice(probabilities)]
9
10
KeyError: 0.050000000000000003
答
看的文档:https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html
的接口是numpy.random.choice(一个,大小=无,替换=真,P =无) 。
a是要选择的单词数量,即len(概率)。
大小可以保持默认值无因为您只需要一个预测。
替换应该保持为True,因为您不想删除选中的单词。
并且p =概率。
所以你要拨打:
np.random.choice(len(probabilities), p=probabilities)
你会得到0之间的一个数字NUM_WORDS-1,你这时就需要相应的映射(双射和您的概率排序匹配),以您的单词ID,并用作int_to_vocab的参数。
添加一个案例? – Divakar
你必须使用numpy吗? – Olian04
添加样本,是的,我必须使用numpy。 – VansFannel