pytorch_transformers使用之获取bert词向量

之所以使用pytorch_transformers,有两个原因,
第一:pytorch_transformers确实很赞,被称为最先进的自然语言处理预训练模型库;
第二:kashgari、keras_bert、bert-serving-server不支持tensorflow2.0;
我使用的版本是:
TensorFlow version: 2.0.0b1
torch version: 1.2.0+cpu
Python version: 3.7.3

第一步:安装pytorch

进入pytorch官网,选择自己的系统和python版本进行配置,拷贝Run this Command里的内容,在cmd里安装。
pytorch_transformers使用之获取bert词向量_第1张图片

第二步:安装pytorch-transformers,详情请见 https://pypi.org/project/pytorch-transformers/
pip install pytorch-transformers
第三步:下载自己需要的bert预训练模型,解压到对应的目录下

下载链接:https://github.com/google-research/bert#pre-trained-models
pytorch_transformers使用之获取bert词向量_第2张图片

第四步:将bert预训练模型转换为PyTorch版本(非常重要)

使用convert_tf_checkpoint_to_pytorch.py脚本,将TensorFlow checkpoint(以bert_model.ckpt开头的三个文件)和相关的配置文件(bert_config.json)作为输入,并为此配置创建PyTorch版本模型。
详情请见 https://www.cnblogs.com/jfdwd/p/11233477.html

convert_tf_checkpoint_to_pytorch.py 所在的路径 \Python\Lib\site-packages\pytorch_transformers
1. 在cmd里cd G:\Python\Lib\site-packages\pytorch_transformers,进入对应路径下;

2. 输入python convert_tf_checkpoint_to_pytorch.py --tf_checkpoint_path=E:/code/NLP/chinese_L-12_H-768_A-12/bert_model.ckpt --bert_config_file=E:/code/NLP/chinese_L-12_H-768_A-12/bert_config.json --pytorch_dump_path=E:/code/NLP/chinese_L-12_H-768_A-12/pytorch_model.bin
*注:E:/code/NLP/chinese_L-12_H-768_A-12 是bert预训练模型解压后的目录路径*

3. 运行一次这个转换脚本,可以得到一个PyTorch版本模型。可以忽略TensorFlow checkpoint(以bert_model.ckpt开头的三个文件),但要保留配置文件(bert_config.json)和词汇表文件(vocab.txt),因为PyTorch模型也需要这些文件。将bert_config.json复制粘贴重命名为config.json,否则执行pytorch_transformers代码会报错。

pytorch_transformers使用之获取bert词向量_第3张图片
pytorch_transformers使用之获取bert词向量_第4张图片

第五步:敲代码
import torch
from pytorch_transformers import BertTokenizer,BertModel

tokenizer = BertTokenizer.from_pretrained('E:/code/NLP/chinese_L-12_H-768_A-12')
model = BertModel.from_pretrained('E:/code/NLP/chinese_L-12_H-768_A-12')
input_ids = torch.tensor(tokenizer.encode("自然语言处理")).unsqueeze(0)  # Batch size 1
outputs = model(input_ids)
# last_hidden_states = outputs[0]  # The last hidden-state is the first element of the output tuple
sequence_output = outputs[0]
pooled_output = outputs[1]
print(sequence_output)
print(sequence_output.shape)    ## 字向量
print(pooled_output.shape)      ## 句向量

pytorch_transformers使用之获取bert词向量_第5张图片

你可能感兴趣的:(NLP)