1. 程式人生 > 實用技巧 >Pytorch-Bert預訓練模型的使用(呼叫transformers)

Pytorch-Bert預訓練模型的使用(呼叫transformers)

筆記摘抄

1. transformer資料

transformers(以前稱為pytorch-transformers和pytorch-pretrained-bert)

  • 提供用於自然語言理解(NLU)和自然語言生成(NLG)的BERT家族通用結構(BERT,GPT-2,RoBERTa,XLM,DistilBert,XLNet等),包含超過32種、涵蓋100多種語言的預訓練模型。

  • 首先下載transformers包,pip install transformers

  • 其次手動下載模型(直接from transformers import BertModel會從官方的s3資料庫下載模型配置、引數等資訊,在國內並不可用)

    • 下載bert-base-chinese的config.josn,vocab.txt,pytorch_model.bin三個檔案後,放在bert-base-chinese資料夾下,此例中該資料夾放在F:/Transformer-Bert/下。

提前導包:

import numpy as np
import torch 
from transformers import BertTokenizer, BertConfig, BertForMaskedLM, BertForNextSentencePrediction
from transformers import BertModel

model_name = 'bert-base-chinese'
MODEL_PATH = 'F:/Transformer-Bert/bert-base-chinese/'

# a. 通過詞典匯入分詞器
tokenizer = BertTokenizer.from_pretrained(model_name)
# b. 匯入配置檔案
model_config = BertConfig.from_pretrained(model_name)
# 修改配置
model_config.output_hidden_states = True
model_config.output_attentions = True
# 通過配置和路徑匯入模型
bert_model = BertModel.from_pretrainedo(MODEL_PATH, config = model_config)

利用分詞器進行編碼:

  • encode僅返回input_ids

  • encode_plus返回所有編碼資訊

    • input_ids:是單詞在詞典中的編碼

    • token_type_ids:區分兩個句子的編碼(上句全為0,下句全為1)

    • attention_mask:指定 對哪些詞 進行self-Attention操作

print(tokenizer.encode('吾兒莫慌'))   # [101, 1434, 1036, 5811, 2707, 102]

sen_code = tokenizer.encode_plus('這個故事沒有終點', "正如星空沒有彼岸")
# print(sen_code)
# [101, 1434, 1036, 5811, 2707, 102]
#  {'input_ids': [101, 6821, 702, 3125, 752, 3766, 3300, 5303, 4157, 102, 3633, 1963, 3215, 4958, 3766, 3300, 2516, 2279, 102], 
#  'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1], 
#  'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}

將input_ids轉化回token:

print(tokenizer.convert_ids_to_tokens(sen_code['input_ids']))

# ['[CLS]', '這', '個', '故', '事', '沒', '有', '終', '點', '[SEP]', '正', '如', '星', '空', '沒', '有', '彼', '岸', '[SEP]']

將分詞輸入模型,得到編碼: