2017-05-04 95 views
0

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

添加一個案例? – Divakar

+0

你必須使用numpy嗎? – Olian04

+0

添加樣本,是的,我必須使用numpy。 – VansFannel

回答

3

看的文檔: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的參數。