2015-12-08 54 views
2

我能夠使用tensorflow tutorials來訓練語言模型,模型按照code given here保存爲檢查點文件。使用RNN tensorflow語言模型來預測測試語句的概率

save_path = saver.save(sess, "/tmp/model.epoch.%03d.ckpt" % (i + 1)) 

現在我需要恢復的檢查點,並在下面的代碼中使用它:

def run_epoch(session, m, data, eval_op, verbose=False): 
    """Runs the model on the given data.""" 
    epoch_size = ((len(data) // m.batch_size) - 1) // m.num_steps 
    start_time = time.time() 
    costs = 0.0 
    iters = 0 
    state = m.initial_state.eval() 
    for step, (x, y) in enumerate(reader.ptb_iterator(data, m.batch_size, 
                m.num_steps)): 
    cost, state, _ = session.run([m.cost, m.final_state, eval_op], 
           {m.input_data: x, 
            m.targets: y, 
            m.initial_state: state}) 
    costs += cost 
    iters += m.num_steps 

    if verbose and step % (epoch_size // 10) == 10: 
     print("%.3f perplexity: %.3f speed: %.0f wps" % 
      (step * 1.0/epoch_size, np.exp(costs/iters), 
      iters * m.batch_size/(time.time() - start_time))) 

    return np.exp(costs/iters) 

我無法找到編碼測試句子並得到從訓練的關卡模式句子概率輸出的任何方式。

的教程何況下面的代碼:

probabilities = tf.nn.softmax(logits) 

,但是這是訓練,我想不通我怎麼得到實際的概率。 我應該在理想情況下得到的東西,如:

>>getprob('this is a temp sentence') 
>>0.322 

回答

3

我有同樣的問題,我想我找到辦法解決它,但我不是專家,所以意見歡迎!

在PTBModel類,你需要加入這一行:

self._proba = tf.nn.softmax(logits) 

之前(或在)這個循環:

if not is_training: 
     return 

,並添加此屬性:

 @property 
     def proba(self): 
      return self._proba 

現在在run_epoch函數中,您可以使用類似的方法獲得概率:

cost, state, proba, _ = session.run([m.cost, m.final_state, m.proba, eval_op],... 

從這裏你應該可以訪問proba的所有概率。有可能有更好的方法... 希望這個幫助!

+0

默認測試文件是ptb.text.txt,只需用您的句子替換該文件的內容即可。 – Romain

+0

返回的pobas的形狀是400 * 10000,詞彙大小是vocab_size = 10000,所以如何獲得每個句子的概率?> – stackit

+0

續:對於小模型,所以如何解釋這個 – stackit

0

你應該先知道如何計算得分。由於馬爾可夫假設,我們不需要計算太多(基於鏈式規則)。應該算出的僅僅是下面幾句話的概率(爲了方便起見,我們說一個)。然後鍵變成如何計算下一個詞的速率。

probab = session.run(myours.proba], feed_dict) # only the input is needed 

您應該創建一個型號命名myours中描述@羅曼的答案(我只是一個是互補)。並創建自己的ptb_iterator來產生只有x(首先你應該使用raw_input或其他來獲取你的單詞,例如在一個循環中)。

for i in range(epoch_size):     
    x = data[:, i*num_steps:(i+1)*num_steps] 
    yield x # the old one with y is better, use y to locate the probability of the coming word 

既然您有可能完成語言模型可以做的所有事情。例如預測下一個單詞。

list(probab[0]).index(max(probab[0])) # an id_to_word dict should be created 

您將獲得N-1的分數(更確切的n-1和詞彙長度的概率分佈,你應該根據未來的字的索引選擇一個)用於n詞的句子。

我用這種方式來計算分數(不是一定的,如果它是對還是錯呢,我遇到同樣的問題,因爲this one):

pro += math.log(list(probab[0])[y[0]], 2) 

PS:

  1. 要保存您可以在第一次訓練網絡時將變量保存在會話中,並在您每次想自己進行測試時恢復它。

    save_path = saver.save(session,「./tmp/model.epoch.%03d.ckpt」%(i + 1)) saver.restore(session,「./tmp/model.epoch.013 .ckpt「)#只持續一個

  2. 一個句子到IDS功能還需要:

    回報[word_to_id [文字]如果字word_to_id在nltk.tokenize.word_tokenize其他word_to_id ["<unk>"對於字(句子)]

希望這有助於解釋eno呃回答你的問題。