首页 > 解决方案 > 使用 Elmo 模型预测句子中的掩码词

问题描述

我有一个作业,要求我构建一个可以从句子中猜出缺失单词的算法。例如,当输入句子是:“I take my **** for a walk this morning”时,我希望输出猜测丢失的单词(dog)。我的任务要求我从头开始训练自己的模型。我建立了我的语料库,它有大约 500.000 个句子。我清理了语料库。它都是小写的,每个句子都用换行符 (\n) 分隔。我也有 words.txt 文件,它按频率降序列出所有唯一单词。词汇文件以前 3 行 'S'、'/S' 和 'UNK' 开头(这 3 个标记在词汇表中用 <> 包围,但在本网站中使用 <> 会出于某种原因隐藏它们之间的字符) .

我按照https://github.com/allenai/bilm-tf中的说明进行操作,它提供了使用 Elmo 从头开始​​训练您自己的模型的步骤。

在收集了 data.txt 和词汇文件后,我使用了

python bin/train_elmo.py --train_prefix= <path to training folder> --vocab_file <path to vocab file> --save_dir <path where models will be checkpointed>`

并使用 tensorflow 和启用 CUDA 的 gpu 训练我的语料库。

训练完成后,我使用了以下命令:

python bin/dump_weights.py --save_dir /output_path/to/checkpoint --outfile/output_path/to/weights.hdf5

这给了我 weights.hdf5 和 options.json 文件。我在训练模型时收到的唯一警告是:

WARNING : Error encountered when serializing lstm_output_embeddings.Type is unsupported, or the types of the items don't match field type in CollectionDef. 'list' object has no attribute 'name'

在 AllenAI repo 中提到它是无害的。因此可以安全地假设模型训练阶段已正确完成。我的问题是,在此之后我不知道该怎么做。在这个 stackOverflow 链接Predicting Missing Words in a sentence - Natural Language Processing Model中,答案表明可以使用以下代码来预测丢失的单词:

import torch
from pytorch_pretrained_bert import BertTokenizer, BertModel,BertForMaskedLM

# OPTIONAL: if you want to have more information on what's happening,activate the logger as follows
import logging
logging.basicConfig(level=logging.INFO)

# Load pre-trained model tokenizer (vocabulary)
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')

text = '[CLS] I want to [MASK] the car because it is cheap . [SEP]'
tokenized_text = tokenizer.tokenize(text)
indexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text)

# Create the segments tensors.
segments_ids = [0] * len(tokenized_text)

# Convert inputs to PyTorch tensors
tokens_tensor = torch.tensor([indexed_tokens])
segments_tensors = torch.tensor([segments_ids])

# Load pre-trained model (weights)
model = BertForMaskedLM.from_pretrained('bert-base-uncased')
model.eval()

# Predict all tokens
with torch.no_grad():
predictions = model(tokens_tensor, segments_tensors)

predicted_index = torch.argmax(predictions[0, masked_index]).item()
predicted_token = tokenizer.convert_ids_to_tokens([predicted_index])[0]

print(predicted_token)

不幸的是,上面的代码是针对 Bert 模型的。我的任务要求我使用 Elmo 模型。我试图为 Elmo 找到一个类似于 pytorch_pretrained_bert的库,但我找不到任何东西。我可以做些什么来使用我的 Elmo 模型来预测被屏蔽的单词?

谢谢。

标签: pythonmachine-learningnlpallennlpelmo

解决方案


推荐阅读