Issue
I have created script for binary (0 and 1) text classification using XLM-ROBERTa model. I would like to put metrics (as Binary Cross-Entropy) but also early stopping with patience of 15.
But I have a problem. I tried to use the path model.compile and model.fit, but XLM-RoBertaForSequenceClassification doesn't have these parameters. I would't like to use Argumentation. It is possible to find some solution?
Already I use AdamW. Finally it is possible to get for each epoch parameters as recall, f1, accuracy? At the moment I get only last data of the last epoch.
Below I put the script during training:
from transformers import XLMRobertaForSequenceClassification, AdamW, BertConfig
# Load BertForSequenceClassification, the pretrained BERT model with a single
# linear classification layer on top.
model = XLMRobertaForSequenceClassification.from_pretrained(
"xlm-roberta-base", # Use the 12-layer BERT model, with an uncased vocab.
num_labels = 2, # The number of output labels--2 for binary classification.
# You can increase this for multi-class tasks.
output_attentions = False, # Whether the model returns attentions weights.
output_hidden_states = False, # Whether the model returns all hidden-states.
)
# Tell pytorch to run this model on the GPU.
#model.cuda()
model.to(device)
Here start the training!
import random
import numpy as np
import gc
seed_val = 45
epochs = 15
# Set the seed value all over the place to make this reproducible.
random.seed(seed_val)
np.random.seed(seed_val)
torch.manual_seed(seed_val)
torch.cuda.manual_seed_all(seed_val)
# Store the average loss after each epoch so we can plot them.
loss_values = []
training_stats = []
# Measure how long the training epoch takes.
total_t0 = time.time()
# For each epoch...
for epoch in range(0, epochs):
print("")
print('======== Epoch {:} / {:} ========'.format(epoch + 1, epochs))
stacked_val_labels = []
targets_list = []
# ========================================
# Training
# ========================================
print('Training...')
# put the model into train mode
model.train()
# This turns gradient calculations on and off.
torch.set_grad_enabled(True)
# Measure how long the training epoch takes.
t0 = time.time()
# Reset the total loss for this epoch.
total_train_loss = 0
for i, batch in enumerate(train_dataloader):
train_status = 'Batch ' + str(i) + ' of ' + str(len(train_dataloader))
print(train_status, end='\r')
b_input_ids = batch[0].to(device)
b_input_mask = batch[1].to(device)
b_labels = batch[2].to(device)
model.zero_grad()
outputs = model(b_input_ids,
attention_mask=b_input_mask,
labels=b_labels)
# Get the loss from the outputs tuple: (loss, logits)
loss = outputs[0]
# Convert the loss from a torch tensor to a number.
# Calculate the total loss.
total_train_loss = total_train_loss + loss.item()
# Zero the gradients
optimizer.zero_grad()
# Perform a backward pass to calculate the gradients.
loss.backward()
# Clip the norm of the gradients to 1.0.
# This is to help prevent the "exploding gradients" problem.
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
# Use the optimizer to update the weights.
# Optimizer for GPU
optimizer.step()
# Optimizer for TPU
# https://pytorch.org/xla/
#xm.optimizer_step(optimizer, barrier=True)
# Measure how long this epoch took.
training_time = format_time(time.time() - t0)
print("")
print('Train loss:' ,total_train_loss)
print(" Training epcoh took: {:}".format(training_time))
# ========================================
# Validation
# ========================================
print('\nValidation...')
# Measure how long the training epoch takes.
t0 = time.time()
# Put the model in evaluation mode.
model.eval()
# Turn off the gradient calculations.
# This tells the model not to compute or store gradients.
# This step saves memory and speeds up validation.
torch.set_grad_enabled(False)
# Reset the total loss for this epoch.
total_val_loss = 0
for j, batch in enumerate(val_dataloader):
val_status = 'Batch ' + str(j) + ' of ' + str(len(val_dataloader))
print(val_status, end='\r')
b_input_ids = batch[0].to(device)
b_input_mask = batch[1].to(device)
b_labels = batch[2].to(device)
outputs = model(b_input_ids,
attention_mask=b_input_mask,
labels=b_labels)
# Get the loss from the outputs tuple: (loss, logits)
loss = outputs[0]
# Convert the loss from a torch tensor to a number.
# Calculate the total loss.
total_val_loss = total_val_loss + loss.item()
# Get the preds
preds = outputs[1]
# Move preds to the CPU
val_preds = preds.detach().cpu().numpy()
# Move the labels to the cpu
targets_np = b_labels.to('cpu').numpy()
# Append the labels to a numpy list
targets_list.extend(targets_np)
if j == 0: # first batch
stacked_val_preds = val_preds
else:
stacked_val_preds = np.vstack((stacked_val_preds, val_preds))
# Calculate the validation accuracy
y_true = targets_list
y_pred = np.argmax(stacked_val_preds, axis=1)
val_acc = accuracy_score(y_true, y_pred)
# Measure how long the validation run took.
validation_time = format_time(time.time() - t0)
print('Val loss:' ,total_val_loss)
print('Val acc: ', val_acc)
print(" Validation took: {:}".format(validation_time))
# Record all statistics from this epoch.
#training_stats = []
training_stats.append(
{
'epoch': epoch + 1,
'Training Loss': total_train_loss,
'Valid. Loss': total_val_loss,
'Valid. Accur.': val_acc,
'Training Time': training_time,
'Validation Time': validation_time
}
)
print("")
print("Training complete!")
print("Total training took {:} (h:mm:ss)".format(format_time(time.time()-total_t0)))
# Save the Model
torch.save(model.state_dict(), '/content/drive/MyDrive/model/model.pt')
# Use the garbage collector to save memory.
gc.collect()
Solution
XLMRobertaForSequenceClassification and other classes of the "ForSequenceClassification" family assume classification into multiple classes and use categorical cross-entropy as the loss function. The class is just a lightweight wrapper of the XLMRoberta class.
If you want to use specifically binary cross-entropy, you can either make your own wrapper with a single class output and binary cross-entropy, or you can do the loss computation in the training loop in your code snippet. I.e., instead of using outputs[0], use the logits outputs[1] as an input to the loss function.
Regarding other metrics, you have the logits in the outputs variable. It should be enough to compute whatever metric you find useful for your task.
Answered By - Jindřich Answer Checked By - Dawn Plyler (Python.Easybugfix Volunteer)
Post a Comment
Post a Comment