Python3.7+transformers3.4.0环境下能否使用ProsusAI/finbert预训练模型?
在transformers 3.4.0(Python3.7)环境下使用ProsusAI/finbert的方案
我尝试运行以下代码:
from transformers import AutoTokenizer, AutoModel t = "ProsusAI/finbert" tokenizer = AutoTokenizer.from_pretrained(t) model = AutoModel.from_pretrained(t)
出现如下错误,确认是transformers版本过旧不支持该模型导致:
/usr/local/lib/python3.7/dist-packages/transformers/configuration_utils.py in get_config_dict(cls, pretrained_model_name_or_path, **kwargs) 380 f"- or '{pretrained_model_name_or_path}' is the correct path to a directory containing a {CONFIG_NAME} file\n\n" 381 ) --> 382 raise EnvironmentError(msg) 383 384 except json.JSONDecodeError: OSError: Can't load config for 'ProsusAI/finbert'. Make sure that: - 'ProsusAI/finbert' is a correct model identifier listed on 'https://huggingface.co/models' - or 'ProsusAI/finbert' is the correct path to a directory containing a config.json file
当前环境版本:
- Python 3.7
- transformers 3.4.0
约束条件:
- transformers 3.4.0是适配Python3.7的最高版本
- 需依赖仅支持Python3.7的multimodal-transformers完成文本+分类列的分类任务,无法升级Python到3.9
问题:能否在旧版transformers环境下使用ProsusAI/finbert?或者有什么替代方案?
可行解决方案
方案1:手动下载模型并适配旧版transformers
- 将
ProsusAI/finbert的核心文件(config.json、pytorch_model.bin、vocab.txt等)下载到本地目录 - 修改
config.json适配旧版格式:- 确保
architectures字段使用旧版支持的名称(比如改为"BertModel",去掉可能的新增后缀) - 删除旧版transformers不识别的冗余元数据字段
- 确保
- 加载模型时指定本地路径,必要时替换为具体的BERT类而非Auto类:
# 替换Auto类为具体BERT类提升兼容性 from transformers import BertTokenizer, BertModel tokenizer = BertTokenizer.from_pretrained("./local_finbert_dir") model = BertModel.from_pretrained("./local_finbert_dir")
方案2:选用旧版兼容的同类型模型
如果手动适配成本高,可直接使用transformers 3.4.0支持的金融领域预训练模型,比如:
yiyanghkust/finbert-tone:发布时间较早,与旧版transformers兼容性更好- 基础BERT模型(如
bert-base-uncased):在自有金融数据集上微调,达到类似效果
方案3:修改multimodal-transformers适配更高版本transformers(进阶)
若必须使用ProsusAI/finbert,可尝试:
- 升级transformers到4.x系列中支持Python3.7的最高版本(如4.28.x)
- 修改multimodal-transformers中与transformers相关的调用代码,适配新版本API(替换已废弃方法、调整参数格式)
内容的提问来源于stack exchange,提问作者Learner91
相关产品推荐
相关产品推荐

