How can I fine-tune a pre-trained transformer model for sentiment analysis?
Asked on Sep 29, 2025
Answer
Fine-tuning a pre-trained transformer model for sentiment analysis involves adapting the model to your specific dataset and task. This process typically includes adding a classification layer and training the model on your labeled sentiment data.
<!-- BEGIN COPY / PASTE -->
from transformers import BertTokenizer, BertForSequenceClassification, Trainer, TrainingArguments
from datasets import load_dataset
# Load a pre-trained BERT model and tokenizer
model_name = "bert-base-uncased"
tokenizer = BertTokenizer.from_pretrained(model_name)
model = BertForSequenceClassification.from_pretrained(model_name, num_labels=2)
# Load and preprocess the dataset
dataset = load_dataset("imdb")
def tokenize_function(examples):
return tokenizer(examples["text"], padding="max_length", truncation=True)
tokenized_datasets = dataset.map(tokenize_function, batched=True)
# Define training arguments
training_args = TrainingArguments(
output_dir="./results",
num_train_epochs=3,
per_device_train_batch_size=8,
evaluation_strategy="epoch"
)
# Initialize Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_datasets["train"],
eval_dataset=tokenized_datasets["test"]
)
# Fine-tune the model
trainer.train()
<!-- END COPY / PASTE -->Additional Comment:
- Fine-tuning involves updating the weights of the model on your specific dataset, which helps the model adapt to the nuances of your task.
- Ensure your dataset is properly labeled for sentiment (e.g., positive/negative) and split into training and evaluation sets.
- Adjust hyperparameters such as learning rate, batch size, and number of epochs based on your dataset size and computational resources.
- Evaluate the model's performance using metrics like accuracy or F1-score to ensure it meets your requirements.
Recommended Links: