max_length不会修复问答模型



我的问题:在给定一个大(>512b(.txt文件的情况下,如何运行我的"问答"模型?

上下文:我正在用谷歌的单词嵌入模型BERT创建一个问答模型。当我导入一个包含几句话的.txt文件时,该模型运行良好,但当.txt文件超过512b个单词的限制作为模型学习的上下文时,模型不会回答我的问题。

我尝试解决问题:我在编码部分设置了一个max_length,但这似乎并不能解决问题(我的尝试代码如下(。

from transformers import AutoTokenizer, AutoModelForQuestionAnswering
import torch
max_seq_length = 512

tokenizer = AutoTokenizer.from_pretrained("henryk/bert-base-multilingual-cased-finetuned-dutch-squad2")
model = AutoModelForQuestionAnswering.from_pretrained("henryk/bert-base-multilingual-cased-finetuned-dutch-squad2")
f = open("test.txt", "r")
text = str(f.read())
questions = [
"Wat is de hoofdstad van Nederland?",
"Van welk automerk is een Cayenne?",
"In welk jaar is pindakaas geproduceerd?",
]
for question in questions:
inputs = tokenizer.encode_plus(question, 
text, 
add_special_tokens=True, 
max_length=max_seq_length,
truncation=True,
return_tensors="pt")
input_ids = inputs["input_ids"].tolist()[0]
text_tokens = tokenizer.convert_ids_to_tokens(input_ids)
answer_start_scores, answer_end_scores = model(**inputs, return_dict=False)
answer_start = torch.argmax(
answer_start_scores
)  # Get the most likely beginning of answer with the argmax of the score
answer_end = torch.argmax(answer_end_scores) + 1  # Get the most likely end of answer with the argmax of the score
answer = tokenizer.convert_tokens_to_string(tokenizer.convert_ids_to_tokens(input_ids[answer_start:answer_end]))
print(f"Question: {question}")
print(f"Answer: {answer}n")

编码结果:

> Question: Wat is de hoofdstad van Nederland?
> Answer: [CLS]
>
> Question: Van welk automerk is een Cayenne?
> Answer: [CLS]
>
> Question: In welk jaar is pindakaas geproduceerd?
> Answer: [CLS]

可以看到,模型只返回[CLS]-令牌,这发生在令牌化器编码部分。

EDIT:我发现解决这个问题的方法是通过.txt文件进行迭代,这样模型就可以通过迭代找到答案

EDIT:我发现解决这个问题的方法是通过.txt文件进行迭代,这样模型就可以通过迭代找到答案。模型之所以用[CLS]回答,是因为它在512b上下文中找不到答案,所以它必须更深入地研究上下文。

通过创建这样的循环:

with open("sample.txt", "r") as a_file:
for line in a_file:
text = line.strip()
print(text)

可以将迭代的文本应用到encode_plus中。

最新更新