基于Hugging Face Transformers的问答任务中,torch.argmax()因输入类型错误抛出TypeError的问题求助
解决TypeError: argmax()输入必须是Tensor而非str的问题
看起来你遇到的问题是start_scores的类型不对——它变成了字符串而不是PyTorch张量,导致torch.argmax()无法处理。下面是几种可能的原因和对应的解决方法:
最可能的原因:Transformers版本兼容问题
在较新的Transformers库(v4.x及以上)中,BertForQuestionAnswering的forward方法返回的是一个QuestionAnsweringModelOutput对象,而不是直接返回两个张量元组。如果你直接用start_scores, end_scores = model(...)来解包,会导致变量获取错误(甚至可能意外得到字符串类型)。
解决方案:
修改模型调用的代码,通过对象属性来获取正确的张量:
# 替换原来的start_scores, end_scores = model(...) outputs = model(input_ids=torch.tensor([inputs]), token_type_ids=torch.tensor([sentence_embedding])) start_scores = outputs.start_logits end_scores = outputs.end_logits # 然后再计算索引 start_index = torch.argmax(start_scores) end_index = torch.argmax(end_scores)
额外的排查步骤
如果上面的方法没解决问题,你可以先在报错行前添加打印语句,确认start_scores的类型和内容:
print("Type of start_scores:", type(start_scores)) print("Content of start_scores:", start_scores) start_index = torch.argmax(start_scores)
这能帮你更精准定位问题——比如是否是变量名冲突(比如你在代码其他地方不小心把start_scores赋值成了字符串),或者模型加载是否异常。
小优化建议
你的问题和段落里用了HTML实体",可以替换成普通的双引号,避免tokenizer可能出现的意外处理:
question = 'Why was the student group called "the Methodists?"' paragraph = ''' The movement which would become The United Methodist Church began in the mid-18th century within the Church of England. A small group of students, including John Wesley, Charles Wesley and George Whitefield, met on the Oxford University campus. They focused on Bible study, methodical study of scripture and living a holy life. Other students mocked them, saying they were the "Holy Club" and "the Methodists", being methodical and exceptionally detailed in their Bible study, opinions and disciplined lifestyle. Eventually, the so-called Methodists started individual societies or classes for members of the Church of England who wanted to live a more religious life. '''
内容的提问来源于stack exchange,提问作者Niloofar Adelkhani
相关产品推荐
相关产品推荐

