首页 > 解决方案 > 如何使用微调的 BERT 模型进行句子编码?

问题描述

我按照这里的脚本在我自己的数据集上微调了 BERT 基础模型:

https://github.com/cedrickchee/pytorch-pretrained-BERT/tree/master/examples/lm_finetuning

我将模型保存为.pt文件,现在我想将其用于句子相似性任务。不幸的是,我不清楚如何加载微调模型。我尝试了以下方法:

model = BertModel.from_pretrained('trained_model.pt')
model.eval()

这行不通。它说:

ReadError: not a gzip file

显然,使用该方法加载.pt文件from_pretrained是不可能的。有谁可以帮我离开这里吗?非常感谢!!:)

编辑:我将模型保存在 s3 存储桶中,如下所示:

# Convert model to buffer
buffer = io.BytesIO()
torch.save(model, buffer)
# Save in s3 bucket
output_model_file = output_folder + "trained_model.pt"
s3_.put_object(Bucket="power-plant-embeddings", Key=output_model_file, Body=buffer.getvalue())

标签: pythonnlppytorchbert-language-modelhuggingface-transformers

解决方案


要加载模型,BertModel.from_pretrained()您需要使用save_pretrained() (link)保存它。

任何其他存储方法都需要相应的负载。我不熟悉 S3,但我假设您可以使用get_object (link)检索模型,然后使用 huggingface api 保存它。从此,您应该可以from_pretrained()正常使用了。


推荐阅读