Skip to main content

Fine-tuning BERT for Text Classification

BERT is a pre-trained Transformer model that can understand the meaning and context of text. Instead of training BERT from scratch, we load a pre-trained BERT model and fine-tune it on our own classification dataset. A typical workflow is:

1. What is Hugging Face Transformers?

Hugging Face Transformers is a Python library that provides pre-trained NLP models such as:
  • BERT
  • DistilBERT
  • RoBERTa
  • ALBERT
  • GPT
  • T5
For this example, we will use:

Why use a pre-trained model?

Training BERT from scratch requires huge amounts of data and computational resources. Instead:
This process is called fine-tuning.

2. What is BERT?

BERT = Bidirectional Encoder Representations from Transformers BERT uses the Transformer architecture to understand the relationship between words in a sentence. For example:
and
The word bank has different meanings. BERT uses the surrounding words to understand the context.

3. Pre-trained Model

A pre-trained model has already learned general language patterns from a large text corpus. For example:
Then load the model:
Here:

4. What is Fine-tuning?

Fine-tuning means taking an already trained model and training it further on a smaller, task-specific dataset. For example, suppose we have: Where:
We fine-tune BERT using this dataset.

5. Install Required Libraries

We will use:
  • transformers → BERT and tokenizer
  • datasets → dataset handling
  • evaluate → evaluation metrics
  • torch → PyTorch backend

6. Import Libraries


7. Create a Small Dataset

For learning purposes, we can create our own dataset.
Here:

8. Create Hugging Face Dataset

Example output:

9. Split Dataset

We need training and testing data.
Conceptually:

10. Load BERT Tokenizer

The tokenizer converts text into tokens that BERT understands. For example:
becomes something similar to:
and then gets converted into numerical token IDs.

11. Tokenization

Create a tokenization function:

Important parameters

Makes sequences the same length.
Cuts text if it is too long.
Maximum sequence length is 128 tokens.

12. Apply Tokenization

Now the dataset contains information such as:

13. What is input_ids?

BERT does not directly understand:
The tokenizer converts it into numbers. For example:
These numbers represent vocabulary tokens.

14. What is attention_mask?

The attention mask tells BERT which tokens are real and which are padding. Example:
Meaning:

15. Load Pre-trained BERT

num_labels=2 means:
The architecture is approximately:

16. Define Training Arguments

Important parameters

Learning rate
Controls how much model weights change during training. BERT fine-tuning generally uses a relatively small learning rate. Batch size
Number of examples processed at once. Epochs
The model sees the training dataset three times. Weight decay
Helps reduce overfitting.

17. Create Trainer

The Trainer handles much of the training loop automatically. Instead of manually writing:
Hugging Face’s Trainer handles these operations for us.

18. Start Fine-tuning

During training:
This is the fine-tuning process.

19. Evaluate the Model

You may see output similar to:
Because this is a very small demonstration dataset, the evaluation result is not meaningful as a real-world benchmark. For a real project, use hundreds or thousands of examples.

20. Make Predictions

Let’s create a new sentence:
Tokenize it:
Move inputs to the same device as the model:

21. Get Model Prediction

The model returns logits.
Example:
There are two values because we have two classes:

22. Convert Logits to Class

Example:
Therefore:

23. Complete Prediction Code


24. Complete Example

Here is the complete beginner-friendly implementation in one place:

25. Understanding the Complete Pipeline

The most important part to remember is:
More specifically:

26. Important Hugging Face Classes


27. AutoTokenizer and AutoModel

In modern Hugging Face code, you will often see AutoTokenizer and AutoModel. Instead of:
you can use:
Similarly:
This is useful because the same code can work with different Transformer architectures. For example:
or:
or:

28. Recommended Modern Version

For your learning, I would recommend using the Auto* classes:
This is more flexible and is commonly seen in Hugging Face projects.

29. Fine-tuning vs Feature Extraction

Feature extraction

BERT weights are frozen:

Fine-tuning

BERT weights are updated:
Fine-tuning usually allows the model to adapt better to the specific task.

30. Example Applications

The same approach can be used for:

Sentiment analysis

Spam detection

News classification

Customer complaint classification

Intent classification


31. Binary vs Multi-class Classification

Binary classification

Two classes:
Example:

Three-class classification

Example:

Five-class classification

Example:

32. Key Concepts to Remember

Pre-trained model

A model already trained on a large dataset.

Tokenizer

Converts text into numerical representations.

Fine-tuning

Continues training a pre-trained model on a specific task.

Classification head

The final layer that produces class predictions.

Logits

Raw scores produced by the classification model.

argmax

Selects the class with the highest score.

33. Summary of Each Step

Final mental model