本地加载手动下载的Hugging Face预训练Transformer模型报错求助
我来帮你排查这个问题!先看你遇到的AttributeError,核心原因是**TFPreTrainedModel是一个抽象基类,不能直接用它的from_pretrained()方法实例化模型**——它是所有TensorFlow预训练模型的父类,本身没有绑定具体的模型配置,所以会出现config_class为None的错误。
针对你的场景,我给你两个解决方案,从简单到进阶:
方案1:用Auto系列类自动适配模型(推荐)
用TFAutoModelForSequenceClassification(TensorFlow版本的自动序列分类模型类)替代TFPreTrainedModel,它会自动读取本地文件夹里的config.json,识别出模型是RoBERTa情感分类模型,然后正确加载。同时注意你代码里的一个拼写错误:sentiment-analyis应该是sentiment-analysis(最后少了个s)。
修改后的代码如下:
from transformers import pipeline, TFAutoModelForSequenceClassification, AutoTokenizer import os model_dir = "./models/twitter-roberta-base-sentiment-latest/" print(os.listdir(model_dir)) # 确认文件夹内容 # 用TFAutoModelForSequenceClassification替代TFPreTrainedModel model = TFAutoModelForSequenceClassification.from_pretrained(model_dir) tokenizer = AutoTokenizer.from_pretrained(model_dir) # 修正task名称的拼写错误 analyze = pipeline(task="sentiment-analysis", model=model, tokenizer=tokenizer) print(analyze("this is good")) print(analyze("this is bad"))
方案2:直接用pipeline加载本地文件夹(更简洁)
其实你可以跳过手动实例化模型和tokenizer的步骤,直接让pipeline从本地文件夹加载,它会自动处理所有细节:
from transformers import pipeline model_dir = "./models/twitter-roberta-base-sentiment-latest/" analyze = pipeline("sentiment-analysis", model=model_dir) print(analyze("this is good")) print(analyze("this is bad"))
为什么原来的代码会报错?
再给你补个小知识点:TFPreTrainedModel的设计是作为基类提供通用方法,比如save_pretrained(),但不能直接用来创建模型实例。所有具体的TensorFlow模型类(比如TFRobertaModel、TFRobertaForSequenceClassification)都继承自它,但只有这些具体类才有绑定的config_class,才能正常调用from_pretrained()。
你的本地文件夹里已经有tf_model.h5(TensorFlow模型权重)、config.json(模型配置)、vocab.json(词表)这些必要文件,所以修改后应该能正常运行啦!
备注:内容来源于stack exchange,提问作者Arthur

