开始使用免费开始使用

解码您的预测结果

为了节省等待时间,您的 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.____[____]
编辑并运行代码