繁体   English   中英

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

[英]Add some randomness with numpy.random.choice

我是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

查看文档: https : //docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html

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

a是您要选择的单词数,即len(probabilities)。

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

因为您不想删除选取的单词,所以replace应该保持为True。

和p =概率。

所以你想打电话:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM