StackPractices
advanced By Mathias Paulenko

Fine-Tune and Deploy Text Classifiers with Hugging Face

Fine-tune a pre-trained transformer model for text classification using Hugging Face Trainer, tokenize datasets, evaluate metrics, and deploy for inference

Topics: ai

Overview

Pre-trained transformer models like BERT and DistilBERT already “understand” language — fine-tuning one on your labels turns it into a classifier for your specific task, usually with a few hundred lines of code and a modest GPU. Hugging Face’s transformers library wraps the whole loop in the Trainer API: you provide a tokenized dataset and a metrics function, and it handles batching, optimization, checkpointing, and evaluation.

This recipe walks through the full cycle — loading data, tokenizing, fine-tuning distilbert-base-uncased on IMDb sentiment, evaluating F1, saving the model, and serving batch predictions. If your task is closer to prompting than classification, compare with Build an LLM Fine-Tuning Pipeline or the prompt-side approach in Prompt Engineering Patterns.

When to Use This

  • Sentiment analysis on customer reviews, support tickets, or social media
  • Spam detection, topic routing, or intent recognition with fixed label sets
  • Any classification task where you have labeled data and a fine-tuned model will beat prompt-based approaches on cost and latency

Prerequisites

  • Python 3.10+
  • transformers, datasets, evaluate packages
  • A GPU makes this fast; CPU works for the small subset used here, just expect minutes instead of seconds per epoch

Solution

1. Install Dependencies

pip install transformers datasets evaluate torch accelerate

2. Load and Prepare the Dataset

from datasets import load_dataset, DatasetDict

# Load a sentiment analysis dataset
dataset = load_dataset("imdb")

# Subset for faster training (optional)
train_dataset = dataset["train"].shuffle(seed=42).select(range(2000))
test_dataset = dataset["test"].shuffle(seed=42).select(range(500))

dataset = DatasetDict({
    "train": train_dataset,
    "test": test_dataset,
})

print(dataset)
# DatasetDict({
#     'train': Dataset({features: ['text', 'label'], num_rows: 2000}),
#     'test':  Dataset({features: ['text', 'label'], num_rows: 500}),
# })

3. Tokenize the Dataset

from transformers import AutoTokenizer

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

def tokenize_function(examples):
    return tokenizer(
        examples["text"],
        padding="max_length",
        truncation=True,
        max_length=256,
    )

tokenized_datasets = dataset.map(tokenize_function, batched=True)

# Set format for PyTorch
tokenized_datasets.set_format(
    type="torch",
    columns=["input_ids", "attention_mask", "label"],
)

4. Fine-Tune with Trainer API

from transformers import (
    AutoModelForSequenceClassification,
    TrainingArguments,
    Trainer,
)
import evaluate

# Load pre-trained model with a fresh classification head
model = AutoModelForSequenceClassification.from_pretrained(
    model_name,
    num_labels=2,
)

# Define training arguments
training_args = TrainingArguments(
    output_dir="./results",
    num_train_epochs=3,
    per_device_train_batch_size=16,
    per_device_eval_batch_size=64,
    warmup_steps=100,
    weight_decay=0.01,
    evaluation_strategy="epoch",
    save_strategy="epoch",
    load_best_model_at_end=True,
    metric_for_best_model="f1",
    logging_dir="./logs",
    logging_steps=50,
)

# Load evaluation metrics
f1_metric = evaluate.load("f1")
accuracy_metric = evaluate.load("accuracy")

def compute_metrics(eval_pred):
    logits, labels = eval_pred
    predictions = logits.argmax(axis=-1)
    return {
        "f1": f1_metric.compute(predictions=predictions, references=labels)["f1"],
        "accuracy": accuracy_metric.compute(predictions=predictions, references=labels)["accuracy"],
    }

# Create Trainer
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_datasets["train"],
    eval_dataset=tokenized_datasets["test"],
    compute_metrics=compute_metrics,
)

# Train
trainer.train()

5. Evaluate the Model

eval_results = trainer.evaluate()
print(f"F1 Score: {eval_results['eval_f1']:.4f}")
print(f"Accuracy: {eval_results['eval_accuracy']:.4f}")

6. Save and Deploy

import torch
from transformers import pipeline

# Save the fine-tuned model and tokenizer
model_dir = "./sentiment-classifier"
trainer.save_model(model_dir)
tokenizer.save_pretrained(model_dir)

# Load for inference
classifier = pipeline(
    "text-classification",
    model=model_dir,
    tokenizer=model_dir,
    device=0 if torch.cuda.is_available() else -1,
)

# Predict
result = classifier("This movie was absolutely fantastic!")
print(result)
# [{'label': 'LABEL_1', 'score': 0.9998}]

7. Batch Inference Service

from typing import List
import torch
from transformers import pipeline

class TextClassificationService:
    def __init__(self, model_dir: str):
        self.classifier = pipeline(
            "text-classification",
            model=model_dir,
            tokenizer=model_dir,
            device=0 if torch.cuda.is_available() else -1,
        )
        self.label_map = {0: "negative", 1: "positive"}

    def classify(self, texts: List[str]) -> List[dict]:
        """Classify a batch of texts.

        Args:
            texts: List of input texts.

        Returns:
            List of {label, score, text} dicts.
        """
        results = self.classifier(texts, batch_size=32)
        return [
            {
                "label": self.label_map.get(int(r["label"].split("_")[-1]), r["label"]),
                "score": r["score"],
                "text": text[:100],
            }
            for r, text in zip(results, texts)
        ]

# Usage
service = TextClassificationService("./sentiment-classifier")
predictions = service.classify([
    "Great product, highly recommend!",
    "Terrible experience, would not buy again.",
    "It's okay, nothing special.",
])
for p in predictions:
    print(f"{p['label']}: {p['score']:.3f} — {p['text']}")

The training and inference scripts live in the companion repo.

How It Works

flowchart diagram: Dataset<br/>text + label

The tokenizer converts raw text into token IDs; padding="max_length" makes every sequence the same length so they can batch, and truncation=True clips anything longer than max_length. AutoModelForSequenceClassification takes the pre-trained transformer and swaps the output layer for a classification head — the base weights stay frozen in knowledge, only the head (and gradually the upper layers) adapts to your labels.

Trainer owns the loop: forward pass, loss, backprop, optimizer step, LR schedule, checkpointing, and the periodic evaluation that calls your compute_metrics with logits and true labels. With load_best_model_at_end, the checkpoint it keeps is the one with the best F1, not the last one — important when the model starts to overfit.

At inference, pipeline folds tokenization, the forward pass, softmax, and label decoding into one call. The LABEL_0/LABEL_1 names come from the head’s default id2label; you can bake real names into the model config when saving if you want the pipeline to return “positive”/“negative” directly.

Variants

Multi-Class Classification

# For 3+ classes (e.g., topic classification)
num_labels = 5  # sports, politics, tech, health, entertainment

model = AutoModelForSequenceClassification.from_pretrained(
    model_name,
    num_labels=num_labels,
)

# Use macro F1 for imbalanced multi-class
def compute_metrics(eval_pred):
    logits, labels = eval_pred
    predictions = logits.argmax(axis=-1)
    return {
        "f1_macro": f1_metric.compute(
            predictions=predictions, references=labels, average="macro"
        )["f1"],
    }

Custom Dataset from CSV

from datasets import Dataset

# Load from CSV
dataset = Dataset.from_csv("reviews.csv")  # columns: text, label

# Or from a list of dicts
data = [
    {"text": "Great product!", "label": 1},
    {"text": "Worst purchase ever.", "label": 0},
]
dataset = Dataset.from_list(data)

ONNX Export for Faster Inference

from optimum.onnxruntime import ORTModelForSequenceClassification
from transformers import pipeline

# Export to ONNX
ort_model = ORTModelForSequenceClassification.from_pretrained(
    "./sentiment-classifier",
    export=True,
)
ort_model.save_pretrained("./sentiment-classifier-onnx")

# Use ONNX pipeline (2-4x faster on CPU)
classifier = pipeline(
    "text-classification",
    model=ort_model,
    tokenizer="./sentiment-classifier",
)

Early Stopping

from transformers import EarlyStoppingCallback

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_datasets["train"],
    eval_dataset=tokenized_datasets["test"],
    compute_metrics=compute_metrics,
    callbacks=[EarlyStoppingCallback(early_stopping_patience=3)],
)

Best Practices

Start with DistilBERT — it’s roughly 40% smaller than BERT and keeps ~95% of the accuracy on most classification tasks, which matters both in training time and serving latency. Move up to a bigger model only when the eval metric says DistilBERT isn’t enough.

Keep max_length at 256 or 512. Longer sequences help a little on long documents, but attention cost grows quadratically with length — most short-text classification gains nothing past 256.

Watch the validation F1, not the loss curve. Loss keeps dropping while the model memorizes; load_best_model_at_end plus metric_for_best_model pins the checkpoint where generalization peaked.

Batch size is a memory knob, not an accuracy knob. If you hit OOM, drop per_device_train_batch_size and compensate with gradient_accumulation_steps — the effective batch stays the same.

Common Mistakes

Fine-tuning when you shouldn’t. If you have under ~200 labeled examples per class, a prompted LLM often beats a fine-tuned BERT — fine-tuning shines when you have data and need cheap, fast inference at volume. See the FAQ for the trade-off.

Training on unshuffled or unsplit data. Always shuffle before select(range(n)), and keep a held-out test set the trainer never sees — evaluating on training data produces F1 scores that won’t survive production.

Forgetting num_labels. It defaults to 2; a 5-class problem silently trains a binary head and produces garbage labels.

Leaving LABEL_0/LABEL_1 in production output. Map them to real names (like the service class above) or set id2label in the model config before saving — downstream consumers shouldn’t have to know about internal label IDs.

Further Reading

Frequently Asked Questions

How long does fine-tuning take?

On a single GPU like a T4, fine-tuning DistilBERT on 2,000 examples for 3 epochs takes ~5-10 minutes. On CPU, expect 30-60 minutes — workable for experimentation, painful for iteration.

Can I use this for non-English text?

Yes. Swap the base model for distilbert-base-multilingual-cased, or pick a language-specific checkpoint from the Hugging Face Hub — the rest of the code stays identical.

How many examples do I need?

500-1,000 per class is a comfortable starting point. With fewer, try data augmentation, a model already trained on a similar task, or few-shot prompting instead.

Should I fine-tune or use an LLM with prompts?

Fine-tuned classifiers are faster, cheaper, and often more accurate on a fixed task — inference costs milliseconds on CPU. LLMs win when labels change often, you have little data, or the "classes" are fuzzy. For a lighter baseline before committing to transformers, check Sentiment Analysis with NLTK.

Why did my F1 drop after the first epoch?

Classic overfitting sign: the model memorized the training set. Cut epochs, add EarlyStoppingCallback, or increase weight_decay. With load_best_model_at_end the epoch-1 checkpoint is what gets saved anyway.