開始使用免費開始

解碼你的預測結果

你的 LSTM model 已經訓練完成(細節請見前一題成功訊息),這樣你就不必等待。現在要來定義一個函式來解碼它的預測結果。訓練好的 model 會作為此函式的預設參數傳入。

由於你使用的是含有 softmax 的模型,可以用 numpy 的 argmax() 從輸出機率向量中取得最可能的下一個單字所代表的索引/位置。

你先前建立並擬合過的 tokenizer 已為你載入。你會使用它內部的 index_word 字典,將 model 的下一字預測(為整數)轉換成實際的文字。

你離動手用模型做實驗就差一步了!

本練習屬於課程

Keras 深度學習入門

檢視課程

練習說明

  • 使用 texts_to_sequences() 將參數 test_text 轉成數字序列。
  • test_seq 傳入模型取得下一字預測。對模型輸出的 numpy 陣列呼叫 .argmax(axis=1)[0],即可取得機率最高的單字之索引/位置。
  • 使用 tokenizer 的 index_word 字典,回傳對應此預測索引的單字。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

def predict_text(test_text, model = model):
  if len(test_text.split()) != 3:
    print('Text input should be 3 words!')
    return False
  
  # Turn the test_text into a sequence of numbers
  test_seq = tokenizer.texts_to_sequences([____])
  test_seq = np.array(test_seq)
  
  # Use the model passed as a parameter to predict the next word
  pred = ____.predict(____).argmax(axis = 1)[0]
  
  # Return the word that maps to the prediction
  return tokenizer.____[____]
編輯並執行程式碼