有時候我們并不想使用Transformers
來訓(xùn)練別人的預(yù)訓(xùn)練模型,而是想用來訓(xùn)練自己的模型,并且不想寫訓(xùn)練過程代碼。這時,我們可以按照一定的要求定義數(shù)據(jù)集和模型,就可以使用Trainer
類來直接訓(xùn)練和評估模型,不需要寫那些訓(xùn)練步驟了。
使用Trainer
類訓(xùn)練自己模型步驟如下,以網(wǎng)絡(luò)退化現(xiàn)象和殘差網(wǎng)絡(luò)效果中的殘差模型為例:
導(dǎo)入必要庫
import torch
from torch import nn
from datasets import Dataset
from transformers import Trainer, TrainingArguments
# 驅(qū)動選擇
device = "cuda" if torch.cuda.is_available() else "cpu"
準(zhǔn)備數(shù)據(jù)
X = torch.zeros((26, 26), dtype=torch.float32).to(device=device)
labels = []
for i in range(26):
labels.append((i+1) % 26)
X[i][i] = 1.
labels = torch.tensor(labels)
dataset = Dataset.from_dict({'x':X, 'labels':labels})
-
注意
Trainer
訓(xùn)練時,會將dataset
中的數(shù)據(jù)按照對應(yīng)的鍵值傳入,因此需要在自己模型的forward
方法中接收鍵值變量。如上例,需要將方法寫為:forward(self, x, labels)
構(gòu)建網(wǎng)絡(luò)
# 殘差網(wǎng)絡(luò)
class RN(nn.Module):
def __init__(self):
super(RN, self).__init__()
self.linear_stack = nn.Sequential(
nn.Linear(26, 64),
nn.Hardsigmoid(),
nn.Linear(64, 26),
nn.Hardsigmoid(),
)
self.linear_stack_2 = nn.Sequential(
nn.Linear(26, 64),
nn.Hardsigmoid(),
nn.Linear(64, 64),
nn.Hardsigmoid(),
)
self.output_layer = nn.Linear(64, 26)
self.loss_f = nn.CrossEntropyLoss()
def forward(self, x, labels, mode='train'):
y = self.linear_stack(x)
# 殘差
y = y+x
y = self.linear_stack_2(y)
y = self.output_layer(y)
if mode is 'train':
return {
'loss':self.loss_f(y, labels),
'predictions':y
}
return y
網(wǎng)絡(luò)與之前完全一致,只是改了下前向傳播方法,這里的mode=’train’
是為了后續(xù)自己使用模型加的,也可以不要。
創(chuàng)建Trainer類
# 生成模型實例
model = RN().to(device=device)
def compute_metrics(pred):
labels = pred.label_ids
preds = pred.predictions.argmax(-1)
acc = (labels == preds).sum()/len(labels)
return {
'accuracy': acc,
}
training_args = TrainingArguments(
output_dir='./results', # output directory 結(jié)果輸出地址
num_train_epochs=1000, # total # of training epochs 訓(xùn)練總批次
per_device_train_batch_size=1, # batch size per device during training 訓(xùn)練批大小
per_device_eval_batch_size=1, # batch size for evaluation 評估批大小
logging_dir='./logs/rn_log', # directory for storing logs 日志存儲位置
learning_rate=1e-3, # 學(xué)習(xí)率
save_steps=False, # 不保存檢查點
)
trainer = Trainer(
model=model, # the instantiated ?? Transformers model to be trained 需要訓(xùn)練的模型
args=training_args, # training arguments, defined above 訓(xùn)練參數(shù)
train_dataset=dataset, # training dataset 訓(xùn)練集
eval_dataset=dataset, # evaluation dataset 測試集
compute_metrics=compute_metrics # 計算指標(biāo)方法
)
trainer.train()
trainer.evaluate()
訓(xùn)練過程:
評估結(jié)果:
文章來源:http://www.zghlxwxcb.cn/news/detail-626594.html
保存模型
trainer.save_model()
加載并使用模型
checkpoint = torch.load('./results/pytorch_model.bin')
model = RN().to(device)
model.load_state_dict(checkpoint)
model(X.to(device), torch.tensor(labels).to(device))['predictions'].argmax(1)
文章來源地址http://www.zghlxwxcb.cn/news/detail-626594.html
到了這里,關(guān)于Transformers實戰(zhàn)——使用Trainer類訓(xùn)練和評估自己的數(shù)據(jù)和模型的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!