how to fine tune a nlp model with sample code
- User
how to fine tune a nlp model with sample code
- Assistant
how to fine tune a nlp model with sample code
Fine-tuning an NLP model involves taking a pre-trained model and training it further on a specific task or dataset. Fine-tuning can help improve the performance of the model on the specific task at hand.
Here is some sample code for fine-tuning a pre-trained BERT model on a text classification task:
!pip install transformers
!pip install torch
from transformers import BertForSequenceClassification, BertTokenizer
model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2)
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
We load the pre-trained BERT model with the BertForSequenceClassification class and specify the number of labels for our classification task (in this example, 2).
We also load the tokenizer using the BertTokenizer class.
import pandas as pd
df = pd.read_csv('data.csv')
sentences = df['text'].values
labels = df['label'].values
We load the data from a CSV file using Pandas. In this example, the data has two columns: text contains the input text, and label contains the output label.
input_ids = []
attention_masks = []
for sent in sentences:
encoded_dict = tokenizer.encode_plus(
sent,
add_special_tokens = True,
max_length = 64,
pad_to_max_length = True,
return_attention_mask = True,
return_tensors = 'pt'
)
input_ids.append(encoded_dict['input_ids'])
attention_masks.append(encoded_dict['attention_mask'])
input_ids = torch.cat(input_ids, dim=0)
attention_masks = torch.cat(attention_masks, dim=0)
labels = torch.tensor(labels)
We use the tokenizer to convert our input text into encoded input IDs and attention masks. The inputs are tokenized into a fixed length of 64. We also create tensors for the labels.
from sklearn.model_selection import train_test_split
train_inputs, validation_inputs, train_labels, validation_labels = train_test_split(input_ids,
labels,
random_state=42,
test_size=0.1)
train_masks, validation_masks, _, _ = train_test_split(attention_masks, input_ids,
random_state=42,
test_size=0.1)
We use train_test_split from scikit-learn to split our data into training and validation sets.
from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
from transformers import AdamW, get_linear_schedule_with_warmup
batch_size = 32
train_data = TensorDataset(train_inputs, train_masks, train_labels)
train_sampler = RandomSampler(train_data)
train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=batch_size)
validation_data = TensorDataset(validation_inputs, validation_masks, validation_labels)
validation_sampler = SequentialSampler(validation_data)
validation_dataloader = DataLoader(validation_data, sampler=validation_sampler, batch_size=batch_size)
optimizer = AdamW(model.parameters(), lr = 2e-5, eps = 1e-8)
epochs = 4
total_steps = len(train_dataloader) * epochs
scheduler = get_linear_schedule_with_warmup(optimizer,
num_warmup_steps = 0,
num_training_steps = total_steps)
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
model.to(device)
for epoch in range(epochs):
model.train()
for batch in train_dataloader:
batch = tuple(t.to(device) for t in batch)
b_input_ids, b_input_mask, b_labels = batch
model.zero_grad()
outputs = model(b_input_ids,
attention_mask=b_input_mask,
labels=b_labels)
loss = outputs[0]
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
scheduler.step()
model.eval()
val_loss, val_accuracy = 0, 0
for batch in validation_dataloader:
batch = tuple(t.to(device) for t in batch)
b_input_ids, b_input_mask, b_labels = batch
with torch.no_grad():
outputs = model(b_input_ids,
attention_mask=b_input_mask)
logits = outputs[0]
logits = logits.detach().cpu().numpy()
label_ids = b_labels.to('cpu').numpy()
tmp_val_accuracy = accuracy(logits, label_ids)
val_accuracy += tmp_val_accuracy
val_loss += loss_fn(logits, label_ids)
print("Epoch:", epoch+1, "Val Loss:", val_loss/len(validation_dataloader), "Val Accuracy:", val_accuracy/len(validation_dataloader)))
We create dataloaders for the training and validation sets. We set the optimizer, the learning rate and the number of epochs. We set the device to CUDA if it is available, and to the CPU otherwise. We train the model for the specified number of epochs and compute the loss and accuracy for the validation set.
def predict(model, tokenizer, input_text):
input_ids = tokenizer.encode(input_text, add_special_tokens=True)
input_ids = torch.tensor([input_ids])
attention_mask = torch.tensor([[1] * len(input_ids)])
with torch.no_grad():
outputs = model(input_ids=input_ids.to(device),
attention_mask=attention_mask.to(device))
logits = outputs[0]
return logits.argmax().item()
input_text = "I really enjoyed the movie."
output_label = predict(model, tokenizer, input_text)
We define a predict function to take in input text, encode it using the tokenizer, and make a prediction using the fine-tuned model.
This is just a simple example of fine-tuning a pre-trained NLP model. Fine-tuning can be a complex process and requires careful consideration of the task, the data, and the specific pre-trained model being used.