Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 34

Transfer Learning for Text Classification

This lesson is built with resources from huggingface.co.

Hello! Welcome back to our module on Transformer Architectures.

In our last lesson, you learned the fundamental skill of loading pre-trained models and their corresponding tokenizers using the Hugging Face transformers library. We saw how to use AutoClass to load any model from the Hub and how to get the raw last_hidden_state—the rich, contextual vector representations that are the core output of an encoder model.

Today, we'll make that output useful. Our goal is to apply a pre-trained encoder model for a downstream task like text classification. You'll learn how to take a general-purpose model and specialize it for a specific objective. This process, known as fine-tuning, is one of the most powerful and common practices in modern NLP.

We'll start with the simplest way to use a model, the pipeline API, and then walk through the complete process of fine-tuning a model for sentiment analysis, a classic text classification task.

From Pre-training to Fine-Tuning

Transformer models like BERT gain their impressive language understanding from being pre-trained on enormous amounts of text data (like the entirety of Wikipedia). During this stage, the model learns grammar, context, and facts about the world in a self-supervised way.

However, a pre-trained model on its own doesn't know how to perform a specific task like classification. To do that, we need to fine-tune it. This involves taking the pre-trained model, adding a small, new layer (called a "head") for our specific task, and then training it for a short time on a smaller, labeled dataset.

This two-step process is incredibly efficient. Instead of training a massive model from scratch for every new task, we leverage the general knowledge of the pre-trained model and just "tune" it for our specific needs.

The following images illustrate this concept perfectly.

Large Language Model: Pre-training and Fine-tuning Process
This diagram shows the two phases: **Pre-training** with large, general data to create a base model, followed by **Fine-tuning** with smaller, task-specific data to create a specialized model.
BERT Pre-training and Fine-tuning Procedures
This image provides a more detailed look at the BERT model. On the left is the pre-training phase. On the right, you can see how the same pre-trained BERT model is adapted for different downstream tasks (like classification or question answering) by adding a small output layer.

The Easiest Application: The pipeline API

Before we dive into the fine-tuning process, let's look at the quickest way to use a pre-trained model that has already been fine-tuned for a specific task. The Hugging Face pipeline function is a high-level abstraction that handles all the boilerplate code for you: tokenization, passing inputs through the model, and decoding the output into a human-readable format.

As a software engineer, you can think of the pipeline as a high-level API that gives you a ready-to-use service endpoint for a specific AI task.

Transformers, what can they do?

The following resource from the Hugging Face LLM Course introduces the pipeline function and demonstrates its power and simplicity. It will give you a great overview of what's possible with just a few lines of code.

Please watch the sections 'Working with pipelines' and 'Text pipelines' (timestamps 0:34-1:53 and 2:20-2:38). Focus on understanding the three steps the pipeline automates and see how text-classification fits into the broader set of available tasks.

Let's try it ourselves with sentiment analysis. The pipeline will automatically download a default model that has been fine-tuned for this task.

from transformers import pipeline

# 1. Create a sentiment-analysis pipeline
classifier = pipeline("sentiment-analysis")

# 2. Use it on some text
results = classifier("This course is teaching me exactly what I need to know!")

# 3. Print the results
print(results)

Expected Output:

[{'label': 'POSITIVE', 'score': 0.9998...}]

This is incredibly powerful! With just two lines of code, we performed a sophisticated NLP task. The pipeline is perfect for using off-the-shelf models. But what if we want to train a model on our own data or for a custom task? For that, we need to perform the fine-tuning ourselves.


A Practical Walkthrough: Fine-Tuning for Text Classification

Now, let's roll up our sleeves and build our own text classifier. We'll fine-tune the distilbert-base-uncased model on the IMDb dataset, which contains movie reviews labeled as positive or negative. We'll use the high-level Trainer API from Hugging Face, which simplifies the training process while still showing you the key steps.

The following resource from the Hugging Face documentation provides a complete guide for this process. We will walk through its steps together, and I'll add explanations along the way.

Text classification

This is the official Hugging Face guide for text classification. It will serve as our primary reference for the code in this section. We will be implementing the steps it describes.

I recommend having this guide open as you go through the lesson. We will cover the content from the start through to the 'Inference' section. Don't worry about understanding every single detail immediately; focus on the overall flow from data to trained model.

Step 1: Load and Prepare the Dataset

First, we need data. The Hugging Face datasets library makes it easy to download and work with common datasets. We'll load the IMDb dataset.

# You'll need to install the 'datasets' and 'evaluate' libraries
pip install datasets evaluate
from datasets import load_dataset

# Load the dataset
imdb = load_dataset("imdb")

# Let's inspect it
print(imdb)
# You can check a sample
print(imdb["train"][0])

The dataset is conveniently split into train and test sets. Each item has a text field (the movie review) and a label field (0 for negative, 1 for positive).

Step 2: Preprocess the Data

The model can't work with raw text. We need to tokenize it using the same tokenizer that was used for the model's pre-training.

In the last lesson, you used AutoModel. This time, because our goal is classification, we'll use AutoModelForSequenceClassification. This class automatically loads the DistilBERT model with a sequence classification head on top.

from transformers import AutoTokenizer, AutoModelForSequenceClassification

checkpoint = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)

# This function will tokenize our text
def tokenize_function(examples):
    return tokenizer(examples["text"], padding="max_length", truncation=True)

# Apply the tokenization to the entire dataset using .map()
# The 'batched=True' argument processes multiple elements at once for speed
tokenized_datasets = imdb.map(tokenize_function, batched=True)

The tokenized_datasets now contain the input_ids, attention_mask, etc., that the model needs. The .map() function is a highly efficient way to apply this preprocessing across the entire dataset.

Step 3: Configure the Training

The Trainer API is a powerful utility that encapsulates the entire training loop. To use it, we first need to define the training configuration using the TrainingArguments class. This lets us specify things like the output directory, number of training epochs, batch size, and more.

from transformers import TrainingArguments, Trainer
import numpy as np
import evaluate

# Define where to save the model
training_args = TrainingArguments(output_dir="my_awesome_model")

# Load the model. We specify the number of labels our task has.
model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2)

# We also need a way to compute metrics during training
metric = evaluate.load("accuracy")

def compute_metrics(eval_pred):
    logits, labels = eval_pred
    predictions = np.argmax(logits, axis=-1)
    return metric.compute(predictions=predictions, references=labels)

Here, we've loaded our model and told it to expect 2 labels (positive/negative). We also set up a function compute_metrics that will be called during evaluation to calculate the model's accuracy.

Step 4: Fine-Tune the Model

With everything prepared, the final step is to create a Trainer instance and start the fine-tuning process. The Trainer will handle the device placement (CPU/GPU), the training loop, evaluation, and saving checkpoints.

trainer = Trainer(
    model=model,
    args=TrainingArguments(
        output_dir="my_awesome_classifier",
        evaluation_strategy="epoch",  # Evaluate at the end of each epoch
        num_train_epochs=1,           # For a quick demo, we'll only train for one epoch
        per_device_train_batch_size=8,
        per_device_eval_batch_size=8,
    ),
    train_dataset=tokenized_datasets["train"].shuffle(seed=42).select(range(1000)), # Use a small subset for a quick training demo
    eval_dataset=tokenized_datasets["test"].shuffle(seed=42).select(range(1000)),
    compute_metrics=compute_metrics,
)

# Start fine-tuning!
trainer.train()

Calling trainer.train() kicks off the process. The Trainer iterates through the dataset, feeds batches to the model, calculates the loss, and updates the model's weights to minimize that loss. You'll see a progress bar showing the training loss decreasing. By the end, our model will have learned to classify movie reviews!

Step 5: Inference with Your Fine-Tuned Model

After training, the my_awesome_classifier directory will contain your fine-tuned model. You can now use it for inference just like we did with the pipeline at the beginning, but this time, you point it to your own model.

# Load a pipeline with your fine-tuned model
my_classifier = pipeline("sentiment-analysis", model="my_awesome_classifier")

# Test it on new text
review = "I was not expecting to like this movie, but it was surprisingly good!"
result = my_classifier(review)
print(result)

review_2 = "The acting was wooden and the plot was non-existent."
result_2 = my_classifier(review_2)
print(result_2)

Expected Output:

[{'label': 'LABEL_1', 'score': 0.9...}]
[{'label': 'LABEL_0', 'score': 0.9...}]

Notice the labels are LABEL_1 and LABEL_0. This is because we haven't given them human-readable names yet. But the model is correctly identifying positive (1) and negative (0) sentiment based on the knowledge it gained during fine-tuning.

Test your understanding!

In the Inference section of the Hugging Face Text classification guide we've been following, it shows how to manually replicate the pipeline's results. This involves tokenizing the text, passing it to the model, and applying a softmax function to the output logits.

Question: If the model outputs logits as [-1.5, 2.0], what would the predictions be after applying np.argmax(logits, axis=-1)? What does this prediction correspond to in our IMDb task?

Show answer

The np.argmax function returns the index of the maximum value in the array. For [-1.5, 2.0], the maximum value is 2.0, which is at index 1.

Therefore, the prediction would be 1.

In our IMDb task, a label of 1 corresponds to a positive review. The logits represent the model's raw, unnormalized score for each class (index 0 for 'negative', index 1 for 'positive'). A higher logit for index 1 indicates the model is more confident the review is positive.


Conclusion

In this lesson, you took a major step from simply loading a model to applying it to solve a real-world problem. You have learned one of the most fundamental workflows in applied AI.

Key Takeaways:

  • Downstream Tasks: Pre-trained models are generalists; we adapt them to specific problems called "downstream tasks."
  • Fine-Tuning: This is the process of specializing a pre-trained model by training it for a short period on a task-specific, labeled dataset.
  • The pipeline API: Provides a simple, high-level interface for using already fine-tuned models for standard tasks.
  • The Trainer API: A powerful abstraction that manages the entire fine-tuning workflow, including data handling, training loops, evaluation, and saving the model.
  • Workflow: The end-to-end process is: Load Data -> Preprocess (Tokenize) -> Configure & Train -> Infer.

Next Up:

So far, we've focused on an encoder-only model (DistilBERT) for an understanding task (classification). In the next module, we'll pivot to the other side of the transformer world: decoder-only models like GPT. We will begin by exploring how these models perform autoregressive text generation, the core mechanism that powers everything from autocomplete to advanced chatbots like ChatGPT.