2017-05-04 3 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(サイズ=なし、= Trueの場合、P =なしを置き換える)であります。

aは、選択したい単語の数です。つまり、len(確率)です。

サイズはデフォルトでは1つの予測だけにしておくことができます。

置き換えは、選択した単語を削除しないようにTrueにとどまるべきです。

そしてp =確率。

だからあなたが呼び出したい:

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

あなたは0との間の数を取得しますNUM_WORDS-1、あなたはそれに応じてマッピングする必要があります(全単射と確率のあなたの順序をマッチング)あなたの言葉IDに、 int_to_vocabの引数として使用します。

関連する問題