无法从transformers库导入GPT2ForQuestionAnswering的技术问询
解决
cannot import name 'GPT2ForQuestionAnswering' from 'transformers'错误 问题原因
GPT2ForQuestionAnswering并非Hugging Face Transformers库官方提供的预定义模型类。GPT2的官方实现未针对问答任务封装专门的模型类,直接导入自然会报错。
解决方案
自定义GPT2问答模型
基于GPT2的基础模型,自行搭建适配问答任务的输出层,示例代码如下:from transformers import GPT2Model, GPT2Tokenizer import torch.nn as nn class GPT2ForQuestionAnswering(nn.Module): def __init__(self, config): super().__init__() self.gpt2 = GPT2Model(config) # 添加问答任务所需的起始/结束位置预测头 self.start_logits = nn.Linear(config.hidden_size, 1) self.end_logits = nn.Linear(config.hidden_size, 1) def forward(self, input_ids, attention_mask=None): outputs = self.gpt2(input_ids, attention_mask=attention_mask) last_hidden_state = outputs.last_hidden_state start_scores = self.start_logits(last_hidden_state).squeeze(-1) end_scores = self.end_logits(last_hidden_state).squeeze(-1) return start_scores, end_scores # 初始化模型和分词器 tokenizer = GPT2Tokenizer.from_pretrained("gpt2") model = GPT2ForQuestionAnswering.from_pretrained("gpt2")改用官方支持问答的模型
如果不需要局限于GPT2,可直接使用库中官方维护的问答模型,比如BERT、RoBERTa:# 示例:使用BERT问答模型 from transformers import BertTokenizer, BertForQuestionAnswering tokenizer = BertTokenizer.from_pretrained("bert-base-cased") model = BertForQuestionAnswering.from_pretrained("bert-base-cased")升级Transformers库
确保你的库版本是最新的,避免因版本兼容问题导致的异常,执行以下命令升级:pip install --upgrade transformers
内容的提问来源于stack exchange,提问作者Lofiuiu
相关产品推荐
相关产品推荐

