FinBERT can be fine-tuned for specific financial NLP tasks (like sentiment analysis) using the Huggingface transformers library. The process involves loading a custom dataset, tokenizing the text using the FinBERT tokenizer, and using the Trainer API to run the training loop.
Requirements & Environment:
- Recommended versions:
transformers==4.18.0, pytorch==1.7.1. - Use a GPU for efficient training on large datasets.
Workflow Overview:
- Load Data: Load your dataset (e.g., via
pandas) and ensure missing values in text and label columns are dropped. - Split Data: Use
sklearn.model_selection.train_test_split to create training, validation, and testing sets. - Load Model & Tokenizer: Use
BertForSequenceClassification.from_pretrained('yiyanghkust/finbert-pretrain', num_labels=N) and BertTokenizer.from_pretrained('yiyanghkust/finbert-pretrain'). - Preprocess: Convert pandas DataFrames to Huggingface
Dataset objects and apply tokenization with truncation=True and padding='max_length'. - Train: Define
TrainingArguments and use the Trainer class to execute training. - Evaluate & Save: Use
trainer.predict() on the test set and trainer.save_model() to persist the fine-tuned weights.
from transformers import BertTokenizer, Trainer, BertForSequenceClassification, TrainingArguments
from datasets import Dataset
# 1. Load pretrained model and tokenizer
model = BertForSequenceClassification.from_pretrained('yiyanghkust/finbert-pretrain', num_labels=3)
tokenizer = BertTokenizer.from_pretrained('yiyanghkust/finbert-pretrain')
# 2. Prepare dataset (assuming df_train is a pandas DataFrame)
dataset_train = Dataset.from_pandas(df_train)
dataset_train = dataset_train.map(lambda e: tokenizer(e['sentence'], truncation=True, padding='max_length', max_length=128), batched=True)
dataset_train.set_format(type='torch', columns=['input_ids', 'token_type_ids', 'attention_mask', 'label'])
# 3. Define training arguments
args = TrainingArguments(
output_dir = 'temp/',
evaluation_strategy = 'epoch',
save_strategy = 'epoch',
learning_rate=2e-5,
per_device_train_batch_size=32,
num_train_epochs=5,
load_best_model_at_end=True,
metric_for_best_model='accuracy',
)
# 4. Initialize Trainer and train
trainer = Trainer(
model=model,
args=args,
train_dataset=dataset_train,
eval_dataset=dataset_val,
compute_metrics=compute_metrics
)
trainer.train()
# 5. Save the model
trainer.save_model('finbert-sentiment/')