pytorch 中加载 bert 模型, 获取 词向量

鞠嘉志
2023-12-01
import torch
from transformers import BertTokenizer, BertModel
#MODELNAME='hfl/chinese-bert-wwm-ext' #ok
#MODELNAME ='hfl/chinese-bert-wwm' #ok
#MODELNAME='hfl/rbt3'#ok
#MODELNAME='hfl/rbtl3'#ok
#MODELNAME='hfl/chinese-roberta-wwm-ext-large' #ok
MODELNAME='hfl/chinese-roberta-wwm-ext'  # ok

tokenizer = BertTokenizer.from_pretrained(MODELNAME)
roberta = BertModel.from_pretrained(MODELNAME)

可以根据需要选择不同的模型。

如果它自动下载时出错,报如下异常:

Exception has occurred: OSError
Unable to load weights from pytorch checkpoint file. If you tried to load a PyTorch model from a TF 2.0 checkpoint, please set from_tf=True.

 

清除   ~/.cache/torch/transformers下的所有文件后重试。  ~表示你的 home目录,如root用户就是 /root, 其它用户是 /home/username

 

 

模型来源于哈工大 https://github.com/ymcui/Chinese-BERT-wwm ,需要在pytorch中安装transformers

 

pip install transformers

 

 

使用Huggingface-Transformers
依托于Huggingface-Transformers 2.2.2,可轻松调用以上模型。

tokenizer = BertTokenizer.from_pretrained("MODEL_NAME")
model = BertModel.from_pretrained("MODEL_NAME")
注意:本目录中的所有模型均使用BertTokenizer以及BertModel加载,请勿使用RobertaTokenizer/RobertaModel!

其中MODEL_NAME对应列表如下:

模型名	MODEL_NAME
RoBERTa-wwm-ext-large	hfl/chinese-roberta-wwm-ext-large
RoBERTa-wwm-ext	hfl/chinese-roberta-wwm-ext
BERT-wwm-ext	hfl/chinese-bert-wwm-ext
BERT-wwm	hfl/chinese-bert-wwm
RBT3	hfl/rbt3
RBTL3	hfl/rbtl3

下面为获取 词向量的完整代码

 

import torch
#from pytorch_transformers import BertTokenizer,BertModel
from transformers import BertTokenizer, BertModel
#MODELNAME='hfl/chinese-bert-wwm-ext' #ok
#MODELNAME ='hfl/chinese-bert-wwm' #ok
#MODELNAME='hfl/rbt3'#ok
#MODELNAME='hfl/rbtl3'#ok
MODELNAME='hfl/chinese-roberta-wwm-ext-large' #ok
#MODELNAME='hfl/chinese-roberta-wwm-ext'  # ok
tokenizer = BertTokenizer.from_pretrained(MODELNAME)   #分词词
model= BertModel.from_pretrained(MODELNAME)  #模型

input_ids = torch.tensor(tokenizer.encode("自然语言处理")).unsqueeze(0) 
outputs = model(input_ids)
sequence_output = outputs[0]
pooled_output = outputs[1]
print(sequence_output)
print(sequence_output.shape)    ## 字向量
print(pooled_output.shape)      ## 句向量
print(pooled_output)

 

 类似资料: