Transfer learning is a technique that allows us to use pre-trained models that have already learned patterns from large datasets and adapt them for specific tasks with smaller, task-specific data. This approach helps save time, reduces computational costs and can improve performance when we have limited data for training.
In natural language processing (NLP), Hugging Face provides tools and pre-trained models that allow us to implement transfer learning for a wide range of tasks.
Key Features of Hugging Face for Transfer Learning
Let's see various features of Hugging Face:
- Pre-trained Models: Hugging Face offers a large selection of pre-trained models trained on massive datasets that are ready for fine-tuning. These models cover a range of NLP tasks from text classification to question answering, saving us time and effort in training from scratch.
- Datasets Library: It provides an extensive collection of curated datasets designed for various NLP tasks. This makes it easier to find the right data for fine-tuning, ensuring better model performance on task-specific datasets.
- Simple API: Hugging Face library includes a user-friendly API, simplifying the process of working with transformer models. This reduces the complexity of implementing transfer learning allowing us to focus more on the task rather than technical details.
- Model Hub: Model Hub is a community-driven repository where we can share and download pre-trained models. This feature encourages collaboration and access to a variety of models making it easier for us to find the right pre-trained model for any specific NLP task.
Fine-Tuning a Pre-Trained Model for Multi-Class Classification
Here we will fine-tune a DistilBERT model on the AG News dataset to classify news articles into one of four categories: World, Sports, Business or Sci/Tech. Let's see the various steps involved in this implementation.
Step 1: Setup and Installing Necessary Libraries
Before we start, we need to ensure that the required libraries are installed.
!pip install transformers datasets evaluate -U
Step 2: Log In to Hugging Face Hub
Before uploading the model to Hugging Face, we must authenticate our session using our Hugging Face account. This step allows us to store models on the Hugging Face Model Hub making it easy to share and deploy models.
from huggingface_hub import notebook_login
notebook_login()
Step 3: Importing Required Libraries
Here we will be importing all the necessary modules for loading the dataset, training the model and evaluating performance.
from datasets import load_dataset
from transformers import Trainer
from transformers import AutoTokenizer
from transformers import pipeline
from transformers import TrainingArguments
from transformers import DataCollatorWithPadding
from transformers import AutoModelForSequenceClassification
import numpy as np
import evaluate
Step 4: Loading the Dataset
Now we'll load the AG News dataset which is available in Hugging Face’s datasets library. This dataset contains news articles that will be used for multi-class classification (World, Sports, Business, Sci/Tech).
dataset = load_dataset("ag_news")
Step 5: Loading Tokenizer and Tokenizing the Dataset
We load the pre-trained DistilBERT tokenizer which converts text into numerical tokens that the model can process. Next we apply the tokenizer to the dataset, ensuring that each article is tokenized into input IDs.
- token_data = dataset.map(tokenize_function, batched=True): Applies the tokenize_function to the entire dataset in batches to tokenize the text.
- batch_collator = DataCollatorWithPadding(tokenizer=tokenizer): Initializes a batch collator that will dynamically pad the sequences in a batch so they have consistent lengths.
pretrained_model_name = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name)
def tokenize_function(row):
return tokenizer(row["text"], truncation=True)
token_data = dataset.map(tokenize_function, batched=True)
token_data = token_data.remove_columns(["text"])
token_data = token_data.rename_column("label", "labels")
token_data.set_format("torch")
small_train_dataset = token_data["train"].shuffle(seed=42).select(range(1000))
small_eval_dataset = token_data["test"].shuffle(seed=42).select(range(1000))
batch_collator = DataCollatorWithPadding(tokenizer=tokenizer)
Output:

Step 6: Preparing the Model for Fine-Tuning
Next we load the pre-trained model for sequence classification. This model will be fine-tuned to classify AG News articles into one of the four categories. We specify the number of classes based on the dataset.
- model = AutoModelForSequenceClassification.from_pretrained(pretrained_model_name, labels=labels): Loads the pre-trained DistilBERT model and specifies the number of output labels for multi-class classification.
labels = dataset["train"].features["label"].num_classes
model = AutomodelForSequenceClassification.from_pretrained(pretrained_model_name, labels=labels)
Step 7: Defining the Evaluation Metric
Here we set up the evaluation metric (accuracy) to assess the performance of the model during training and evaluation. The function compute_metrics will compare the model’s predictions to the true labels and calculate accuracy.
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)
Step 8: Defining Training Arguments
Now we define the training configuration. These parameters control how the model is trained such as the learning rate, batch size, number of epochs and strategies for saving and evaluating the model. We also enable mixed precision (fp16=True) to optimize training on GPUs.
model_name = "distilbert-ag-news-finetuned"
training_args = TrainingArguments(
output_dir=model_name,
learning_rate=2e-5,
per_device_train_batch_size=16,
per_device_eval_batch_size=16,
num_train_epochs=3,
weight_decay=0.01,
fp16=True,
eval_strategy="epoch",
save_strategy="epoch",
logging_strategy="epoch",
load_best_model_at_end=True,
metric_for_best_model="accuracy",
push_to_hub=True,
)
Step 9: Training the Model
The Trainer class is initialized with the model, training arguments and datasets. It handles the entire training loop, including logging, evaluation and optimization.
model_trainer = Trainer(
model=model,
args=training_args,
train_dataset=token_data["train"],
eval_dataset=token_data["test"],
batch_collator=batch_collator,
compute_metrics=compute_metrics,
)
model_trainer.train()
Output:

Step 10: Pushing the Model to Hugging Face Hub
After training, we can push the fine-tuned model to the Hugging Face Model Hub. This makes it publicly available for others to use or continue fine-tuning.
model_trainer.push_to_hub()
Output:

Step 11: Making Predictions Using the Fine-Tuned Model
Once the model is fine-tuned and uploaded, we can use it to make predictions on new, unseen text. Let's see how we can classify a new news article.
Note: Make sure to replace 'your-model-choice' with the actual model name or path you used when fine-tuning the model.
text = "The home team won the championship after a thrilling match."
classifier = pipeline("sentiment-analysis", model=f"your-model-choice/{model_name}")
prediction = classifier(text)
print(prediction)
print(dataset["train"].features["label"].names)
Output:

Applications of Transfer Learning
Transfer learning with Hugging Face can be applied to a range of NLP tasks which help us to tackle complex problems with fewer resources. Some common applications includes:
- Sentiment Analysis: It is the task of classifying text into categories such as positive, negative or neutral. Fine-tuning pre-trained models like BERT on sentiment-labeled datasets allows us to analyze sentiments in customer reviews, social media posts or news articles.
- Named Entity Recognition (NER): In NER, we identify and classify entities such as names, dates and locations. Pre-trained models can be adapted to perform NER for tasks like extracting person names from text or identifying locations in news stories.
- Text Generation: It can also be used to generate coherent text based on a given prompt. Models like GPT-3, after fine-tuning can generate creative text, help with writing tasks or even produce code based on user input.
- Question Answering: Models fine-tuned for question answering can extract relevant answers from a text passage. This is useful for building systems that respond to user queries based on information in documents, websites or books.
Advantages of Transfer Learning
Transfer learning provides various key advantages that make it valuable, especially for NLP tasks:
- Reduces the Need for Large Datasets: Since pre-trained models have already learned useful features from large datasets, they can be adapted to specific tasks using smaller datasets. This is helpful when labeled data for the target task is less.
- Saves Time and Resources: Training models from scratch is computationally expensive and time-consuming. Transfer learning allows us to use pre-trained models, reducing the amount of time and resources needed to train models on new tasks.
- Improves Model Performance: It generally leads to better performance, when the target dataset is small. Pre-trained models have already learned general patterns that make them better at generalizing which leads to improved results compared to starting from scratch.
Limitations of Transfer Learning
Despite its benefits, there are some limitations to consider when using transfer learning:
- Domain Mismatch: If the pre-trained model is trained on data from a domain that’s very different from the target task, fine-tuning may not be as effective. For example, a model trained on news articles may not perform well on technical or medical texts without additional fine-tuning.
- Fine-tuning Costs: While transfer learning reduces the need for large datasets, fine-tuning a model still requires computational resources, especially with large models. This can be costly for organizations that don’t have access to strong hardware.
- Overfitting Risk: Fine-tuning on small datasets can lead to overfitting where the model becomes too specialized to the training data and struggles with new data. It's important to monitor and apply techniques like regularization to minimize this risk.
You can download the source code from here.


