【问题标题】:Type errors with BERT example使用 BERT 示例输入错误
【发布时间】:2021-08-21 05:28:56
【问题描述】:

我是 BERT QA 模型的新手,我正在尝试遵循 this article 中的示例。问题是当我运行附加到示例的代码时,它会产生如下类型错误TypeError: argmax(): argument 'input' (position 1) must be Tensor, not str

这是我尝试运行的代码:

import torch
from transformers import BertForQuestionAnswering
from transformers import BertTokenizer

#Model
model = BertForQuestionAnswering.from_pretrained('bert-large-uncased-whole-word-masking-finetuned-squad')

#Tokenizer
tokenizer = BertTokenizer.from_pretrained('bert-large-uncased-whole-word-masking-finetuned-squad')

question = '''SAMPLE QUESTION"'''

paragraph = '''SAMPLE PARAGRAPH'''
            
encoding = tokenizer.encode_plus(text=question,text_pair=paragraph, add_special=True)

inputs = encoding['input_ids']  #Token embeddings
sentence_embedding = encoding['token_type_ids']  #Segment embeddings
tokens = tokenizer.convert_ids_to_tokens(inputs) #input tokens

start_scores, end_scores = model(input_ids=torch.tensor([inputs]), token_type_ids=torch.tensor([sentence_embedding]))

start_index = torch.argmax(start_scores)

end_index = torch.argmax(end_scores)

answer = ' '.join(tokens[start_index:end_index+1])

问题出现在此代码的第 13 行,我试图在 start_scores 中获取最大元素,说这不是张量。当我尝试打印此变量时,它将“start_logits”显示为字符串。有人知道这个问题的解决方案吗?

【问题讨论】:

    标签: python bert-language-model


    【解决方案1】:

    所以在参考BERT Documentation 之后,我们发现模型输出对象包含多个属性,不仅是开始和结束分数。因此,我们对代码进行了以下更改。

    
    outputs = model(input_ids=torch.tensor([inputs]),token_type_ids=torch.tensor([sentence_embedding]))
    
    start_index = torch.argmax(outputs.start_logits)
    
    end_index = torch.argmax(outputs.end_logits)
    
    answer = ' '.join(tokens[start_index:end_index+1])
    

    总是先参考文档:"D

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-10
      • 1970-01-01
      • 2016-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-08
      • 2021-12-16
      相关资源
      最近更新 更多