使用numpy.random.choice添加一些随机性

时间:2017-05-04 15:14:10

标签: python numpy

我是python中的新手,也是Numpy的新手。

我必须在以下代码中添加一些随机性:

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

1 个答案:

答案 0 :(得分:3)

查看文档:{​​{3}}

接口是numpy.random.choice(a,size = None,replace = True,p = None)。

a是您要从中选择的单词数,即len(概率)。

大小可以保持默认无,因为您只需要一次预测。

替换应保持为True,因为您不想删除已挑选的单词。

p =概率。

所以你想打电话:

np.random.choice(len(probabilities), p=probabilities)

您将获得一个介于0和num_words-1之间的数字,然后您需要相应地映射(双射并匹配您的概率顺序)到您的单词ID,并将其用作int_to_vocab的参数。