transformers库的使用【二】tokenizer的使用,模型的保存自定义
使用標記器(tokenizer)
在之前提到過,標記器(tokenizer)是用來對文本進行預處理的一個工具。
首先,標記器會把輸入的文檔進行分割,將一個句子分成單個的word(或者詞語的一部分,或者是標點符號)
這些進行分割以后的到的單個的word被稱為tokens。
第二步,標記器會把這些得到的單個的詞tokens轉換成為數字,經過轉換成數字之后,我們就可以把它們送入到模型當中。
為了實現這種能把tokens轉換成數字的功能,標記器擁有一個詞表,這個詞匯表是在我們進行實例化并指明模型的時候下載的,這個標記器使用的詞匯表與模型在預訓練時使用的詞匯表相同。
舉個例子說:
from transformers import AutoTokenizer,AutoModelForSequenceClassification
?
Model_name = 'distillery-base-uncashed-finetuned-still-2-english'
?
model=AutoModelForSequenceClassification.from_pretrained(model_name)
?
tokenizer=AutoTokenizer.from_pretrained(model_name)
?
sentence="We are very happy to show you the Transformers library"
?
inputs = tokenizer(sentence)
然后打印一下得到的結果:
print(inputs)
{'input_ids': [101, 2057, 2024, 2200, 3407, 2000, 2265, 2017, 1996, 100, 19081, 3075, 1012, 102],
'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
可以看到,返回值是一個字典,這個字典里面有兩個鍵值對,第一個鍵值對'input_ids'是對輸入的句子轉換成數字以后的結果,并且長度為這個句子的單詞的個數。
第二個'attention_mask'這里面全部都是1,表示讓模型關注里面所有的詞,具體相關的應用后面會再提到。
上面的例子是拿一個句子放入標記器中得到的結果,如果希望一次放入一批(batch)語句,希望將這一批句子都轉換成為數字送到模型里面去,那么你可以這么做
sentences=["We are very happy to show you the Transformers library",
?
"We hope you don't hate it"]
?
Pt_batch = tokenizer(
?
Sentences,
?
padding=True,
?
truncation=True,
?
max_length=512,
?
return_tensors="Pt"
?
)
首先padding屬性是用來指明是否啟用填補。他會自動補全結果中的input_ids以及attention_mask右邊缺失的值。
打印一下結果來看一下:
for key,value in pt_batch.items():
print(f"{key}:{value.numpy().tolist()}")
input_ids: [[101, 2057, 2024, 2200, 3407, 2000, 2265, 2017, 1996, 100, 19081, 3075, 1012, 102], [101, 2057, 3246, 2017, 2123, 1005, 1056, 5223, 2009, 1012, 102, 0, 0, 0]]
attention_mask: [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0]]
可以看到結果中第二個句子的最右邊補充了一些0,這是因為使用了padding屬性,第二個句子沒有第一個句子長,而我們希望得到的結果都是一樣長的,所以會自動的在結尾補充0,并且在attention_mask字段里面也補充了0。
使用模型
當我們對輸入的數據使用標記器進行處理之后,可以直接把它送到模型當中,這些數據會包含所有模型需要的相關信息。
在使用pytorch的時候,你需要可以用下面的方法對字典類型進行解包:
Pt_outputs = pt_model(**pt_batch)
在Transformers中,所有的輸出都是一個元組(tuple)
Print(pt_ourputs)
(tensor([[-4.0833, ?4.3364],
? ? ? ? [ 0.0818, -0.0418]], grad_fn=<AddmmBackward>),)
可以看到得到的結果
接下來使用SoftMax激活函數進行預測,并打印一下最終的結果
Import torch.nn.functional as F
?
pt_predictions = F.softmax(py_output[0],dim=-1)
?
print(pt_predictions)
tensor([[2.2043e-04, 9.9978e-01],
? ? ? ? [5.3086e-01, 4.6914e-01]], grad_fn=<SoftmaxBackward>)
這里輸出的只是經過了softmax函數后得到的結果,那么如果有標簽的時候,需要在使用模型的時候,在label字段指明標簽
import torch
?
pt_output = pt_model(**pt_batch,labels = torch.tensor([1,0]))
在Transformers提供了一個Trainer類來幫助訓練
模型的保存
在模型進行微調之后,可以對模型以及標記器進行保存操作
save_directory='E:/my model/'
?
tokenizer.save_pretrained(save_directory)
?
model.save_pretrained(save_directory)
這樣就可以將模型進行保存
模型的加載
如果想要重新加載之前訓練好并保存的模型,可以使用一個from_pretrained()方法,通過傳入保存了模型的文件夾路徑。
tokenizer = AutoTokenizer.from_pretrained(save_directory)
?
model = AutoModel.from_pretrained(save_directory)
如果希望讀取TensorFlow模型,那么需要一點點改變
model=AutoModel.from_pretrained(save_directory,from_tf=True)
最終,如果在使用模型的時候,你希望得到的不僅僅是最終的輸出,還希望能得到所有的隱藏層狀態以及注意力權重,你可以這樣做:
pt_outputs = pt_model(**pt_batch,output_hidden_states= True,output_attentions=True)
?
All_hidden_states ,all_attentions = pt_outputs[-2:]
訪問代碼
之前用到的AutoModel與AutoTokenizer兩個類實際上可以和任何的預訓練模型一起工作。
在之前的實例中,模型使用的是"distilbert-base-uncashed-finetuned-still-2-enghish",這意味著我們使用的是DistilBERT的結構。
在創建模型的時候用到的AutoModelForSequenceClassification會自動創建一個DistilBertForSequenceCLassification。
如果不使用自動的方式構建,我們可以使用下面的代碼:
from transformers import DistilBertTokenizer,DistilBertForSequenceClassification
?
model_name = "distilbert-base-uncashed-fintuned-still-2-english"
?
model = DistilBertForSequenceClassification.from_pretrain(model_name)
?
tokenizer = DIstilBertTokenizer.from_pretrained(model_name)
自定義模型
如果希望改變的一些參數,來定義自己的特殊的類,那么可以使用模型特定的或者說相關的配置文件(configuration)比如說,在之前用熬的DistilBERT中,可以使用DistilBertConfig來設置隱藏層緯度,dropout rate等等。
具體來說:
from transformers import DIstilBertConfig,DIstilBertTokenizer,DistilBertForSequence
?
config = DistilBertTokenizer(n_heads=8,dim=512,hidden_dim=4*512)
?
tokenizer=DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
?
model = DistilBertForSequenceClassification(config)
如果你希望改變的只是模型的頭,比如說標簽的數量,那么你只需要直接改變模型創建時候的參數即可
from transformers import DIstilBertConfig,DistilBertTokenizer,DistilBertForSequenceClassification
?
model_name='distilbert-base-uncased'
?
model = DistilBertForSequenceClassification.from_pretrained(model_name,num_labels=10)
?
tokenizer = DistilBertTokenizer.from_pretrained(model_name)
?
總結
以上是生活随笔為你收集整理的transformers库的使用【二】tokenizer的使用,模型的保存自定义的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: doker zookeeper kafk
- 下一篇: Pytorch-使用Bert预训练模型微