news 2026/6/15 15:38:06

python bert_score使用本地模型的方法

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
python bert_score使用本地模型的方法

1. 背景

bert_score是一个用于评估文本生成质量的Python库,基于预训练的BERT模型计算参考文本与生成文本之间的语义相似度。它通过比较两个文本的BERT嵌入向量来评估它们的匹配程度,比传统的n-gram匹配方法(如BLEU、ROUGE)更能捕捉语义层面的相似性。一般bert_score 是仅仅支持指定模型名称然后再代码实现里面从Hugging Face上面拉取模型。但是如果我们在有限制的网络环境中在线拉取模型就会失败,比较合适的解决办法就是先将模型下载到本地,然后给bert_score指定模型路径。

2. 支持的模型和语言

bert_score中通过model_type和lang两个参数来执行模型和对应的文本语言。

具体文档可以参考:https://github.com/Tiiiger/bert_score

from bert_score import score candidates = ["The cat sits on the mat."] # 生成文本 references = ["A cat is sitting on the rug."] # 参考文本 # 计算BERTScore P, R, F1 = score(candidates, references, model_type='roberta-large',lang="en") print(f"Precision: {P.mean():.3f}, Recall: {R.mean():.3f}, F1: {F1.mean():.3f}")

3.支持本地模型的方法

3.1 修改源码

1. 在score方法里面可以看到get_model和get_tokenizer两个方法

2.点进去可以看到对应函数的源码

def get_model(model_type, num_layers, all_layers=None): if model_type.startswith("scibert"): model = AutoModel.from_pretrained(cache_scibert(model_type)) elif "t5" in model_type: from transformers import T5EncoderModel model = T5EncoderModel.from_pretrained(model_type) else: model = AutoModel.from_pretrained(model_type) model.eval() if hasattr(model, "decoder") and hasattr(model, "encoder"): model = model.encoder # drop unused layers # ...... return model def get_tokenizer(model_type, use_fast=False): if model_type.startswith("scibert"): model_type = cache_scibert(model_type) if version.parse(trans_version) >= version.parse("4.0.0"): tokenizer = AutoTokenizer.from_pretrained(model_type, use_fast=use_fast) else: assert not use_fast, "Fast tokenizer is not available for version < 4.0.0" tokenizer = AutoTokenizer.from_pretrained(model_type) return tokenizer

3. 修改源码直接将我们的model_path硬编码进去,当然为了更好的适配性,可以将model_path做成一个可选参数,然后传递出去给score函数

def get_model(model_type, num_layers, all_layers=None): model_path = 'xxx' if model_type.startswith("scibert"): model = AutoModel.from_pretrained(cache_scibert(model_type)) elif "t5" in model_type: from transformers import T5EncoderModel model = T5EncoderModel.from_pretrained(model_path) else: model = AutoModel.from_pretrained(model_path) model.eval() def get_tokenizer(model_type, use_fast=False): if model_type.startswith("scibert"): model_type = cache_scibert(model_type) model_path = 'xxx' if version.parse(trans_version) >= version.parse("4.0.0"): tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=use_fast) else: assert not use_fast, "Fast tokenizer is not available for version < 4.0.0" tokenizer = AutoTokenizer.from_pretrained(model_path) return tokenizer

3.2 添加对应的num_layers参数

这里还有一种方法就是通过给model_type传递给本地模型所在的路径。同时传递num_layers参数来指定。

原因是因为其实Transformers里面的xxx.from_pretrained方法其实也是可以支持你配置本地路径来加载的,这里加载模型也不会有问题。但是在bert_score中他是需要提前知道层数来优化计算过程的。这里才是报错的原因。

这一部分代码是在utils文件中。

def calculate_bert_score(original_text: str, polished_text: str, lang: str = "zh",model_type:str=None) -> float: try: # 使用bert_score计算F1分数 score_params = { "verbose": False, "device": "cuda" if torch.cuda.is_available() else "cpu" } if model_type is None: score_params["model_type"] = BERT_MODEL_PATH #指定模型路径 score_params["num_layers"] = BERT_BASE_CHINESE_NUM_LAYERS#执行模型层数(12) else: score_params["model_type"] = model_type P, R, F1 = score([polished_text], [original_text], **score_params) # 返回F1分数(转换为Python float) f1_score = F1.item() if hasattr(F1, 'item') else float(F1) return f1_score except Exception as e: print(f"计算bert_score时出错: {str(e)}") # 如果计算失败,返回一个默认值或者抛出异常 raise
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/15 14:37:11

Qwen3-32B推理优化:响应速度提升50%

Qwen3-32B推理优化&#xff1a;响应速度提升50% 你有没有这样的体验&#xff1f;——刚上线一个基于Qwen3-32B的智能问答系统&#xff0c;客户输入“请分析这份10万字的技术白皮书”&#xff0c;然后……光标开始缓慢闪烁。等了十几秒&#xff0c;第一个字才蹦出来。用户眉头一…

作者头像 李华
网站建设 2026/6/14 18:13:00

腾讯混元发布AI音效生成框架HunyuanVideo-Foley

腾讯混元发布AI音效生成框架HunyuanVideo-Foley 在一段没有声音的视频里&#xff0c;奔跑的人踩过水坑却悄无声息&#xff0c;玻璃碎裂时听不到一丝清脆——这种割裂感正是传统内容创作中长期存在的“感官断层”。音效&#xff0c;这个曾被视作后期点缀的环节&#xff0c;如今…

作者头像 李华
网站建设 2026/6/15 0:33:03

当产品经理开始用 AI Coding工具时,会发生什么?

产品经理真正被卡住的&#xff0c;并不是“不会画原型” 在大多数团队中&#xff0c;产品经理的典型工作路径是&#xff1a;业务抽象 → 需求拆解 → 原型表达 → 技术评审 → 开发排期 → 上线验证 这是一个成熟、规范的流程&#xff0c;但在真实业务环境中&#xff0c;问题往…

作者头像 李华
网站建设 2026/6/14 18:37:03

25 个实用 Shell 脚本:赋能 Linux 运维效率提升

1、检测服务器是否正常假设&#xff0c;当前MySQL服务的root密码为123456&#xff0c;写脚本检测MySQL服务是否正常&#xff08;比如&#xff0c;可以正常进入mysql执行show processlist&#xff09;&#xff0c;并检测一下当前的MySQL服务是主还是从&#xff0c;如果是从&…

作者头像 李华
网站建设 2026/6/14 16:07:24

针对 DeepSeek V3.2 的推理引擎深度优化

本文整理自 2025 年 12 月 14 日的「百度百舸 X SGLang Meetup 北京站」的同名主题分享。 百度百舸基于万卡级生产系统实战经验&#xff0c;面向 DeepSeek V3.2 在推理引擎层面做了深度优化&#xff0c;加快推理速度&#xff0c;降低推理成本&#xff1a;通过轻量级 CP 让长文…

作者头像 李华
网站建设 2026/6/12 11:57:32

三大AI模型联动:多模态视频生成实战

多模态视频生成实战&#xff1a;三大AI引擎的深度协同 在内容创作进入“超高速迭代”时代的今天&#xff0c;单打独斗的AI模型早已无法满足专业级产出的需求。真正能撬动生产力变革的&#xff0c;是多个AI系统之间的智能分工与无缝协作。我们不再追求一个“全能冠军”&#xff…

作者头像 李华