BERT-based Classification

Machine Learning
Introduced by
Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (Google AI Language)
Year
2019
Type
Pre-trained language model with fine-tuning
Family
Deep learning / NLP / CV

What does it do?

BERT-based Classification fine-tunes Google's Bidirectional Encoder Representations from Transformers (BERT) model on a labelled text dataset, replacing the generic pre-trained output with a task-specific classification layer.

The pre-trained model carries deep bidirectional context learned from a large corpus, which supports strong accuracy on short- and medium-length text classification tasks with modest amounts of labelled data. Its suitability depends on input length, available compute and how closely the pre-training data matches the target domain.

The intuition behind the method

BERT reads every word in a sentence with full awareness of all surrounding words in both directions simultaneously — unlike earlier models that read left-to-right or right-to-left. Before fine-tuning, BERT has already absorbed rich language patterns from a massive corpus. To classify text, a thin classification layer is placed on top and the entire model is briefly re-trained on your labelled examples. The model adjusts its internal representations to suit your specific categories while retaining the broad linguistic knowledge it was pre-trained on, allowing strong performance even when labelled data is scarce.

History

BERT was introduced by Devlin et al. at Google AI Language in 2019. Its central idea was bidirectional pre-training using masked language modelling and next-sentence prediction, so that one pre-trained encoder could be fine-tuned for many downstream tasks. The original work reported state-of-the-art results on 11 NLP benchmarks, including GLUE and SQuAD. Derivatives such as RoBERTa and DistilBERT, along with domain-specific variants, followed, and BERT became a common base for applied text classification.

When to use it

Use BERT-based classification when you have labelled text data and need strong accuracy for tasks such as sentiment analysis, topic categorisation, intent detection, or clinical text classification. Devlin et al. (2019) report strong accuracy on many benchmark text tasks, but results on your own data must be confirmed by evaluation. The method can be effective when large annotated corpora are unavailable, because pre-training supplies language priors. How many labelled examples are enough depends on task difficulty and the number of classes, so check learning curves on a validation set rather than relying on a fixed threshold. Prefer it over simpler models (TF-IDF + logistic regression, CNN, LSTM) when linguistic nuance, long-range context, or subtle semantic distinctions drive the task. Avoid it when sequences exceed 512 tokens without special handling, when GPU compute is unavailable or too costly, when real-time inference latency below a few milliseconds is required, or when the domain is highly specialised and very little in-domain pre-training data exists. In such cases, a domain-specific model (BioBERT, LegalBERT) may be more appropriate.

Limitations and considerations

  • The 512-token input limit is set by the model's position embeddings, so longer documents must be truncated, split into chunks, or processed with a long-document architecture.
  • At inference the full Transformer stack runs on every input, so memory use and latency are higher than for lighter models such as DistilBERT or logistic regression over TF-IDF features.
  • With very small labelled sets, fine-tuning can overwrite useful pre-trained weights (catastrophic forgetting) or overfit the classification head. Monitor validation performance to detect this.
  • The learned representations are opaque; explaining a prediction requires add-on tools such as attention visualisation or SHAP, which describe the model only approximately.

Source conditions do not replace independent scientific review or validation by an analysis engine.

Strengths

  • BERT's bidirectional self-attention is pre-trained jointly across the whole sequence, so each token's representation draws on context from both sides. Standard LSTM encoders are usually trained from scratch on the target task, without comparable large-scale bidirectional pre-training.
  • Pre-training on a large corpus supplies language priors, which can make useful accuracy achievable with modest labelled datasets; the amount needed depends on the task.
  • Fine-tuning starts from existing weights and needs only a few epochs over the labelled data, which is far cheaper than training a comparable model from scratch.
  • One architecture with a single classification head covers many text classification tasks without hand-built features such as TF-IDF n-grams.
  • Pre-trained checkpoints are widely available, including BERT-base and BERT-large and domain-specific derivatives such as BioBERT and LegalBERT.

Applications

  • Sentiment analysis of reviews, social-media posts, and survey responses.
  • Topic and intent classification for customer support, chatbots, and content moderation.
  • Clinical text classification: diagnosis coding, clinical note triage, and adverse-event detection.
  • Scientific abstract categorisation and citation screening in systematic reviews.
  • Hate-speech and misinformation detection on social platforms.

How it works

How it works

1

Input text is split into WordPiece tokens and a special [CLS] token is prepended. A [SEP] token marks sentence boundaries. Each token is mapped to a numerical ID and padded or truncated to a fixed maximum sequence length, typically 128 or 512 tokens.

2

The token sequence passes through all BERT Transformer layers. Each layer applies multi-head self-attention so every token can attend to every other token in both directions simultaneously, building rich context-aware representations at each position.

Formula
h = \text{BERT}([\texttt{[CLS]}, w_1, \ldots, w_n])
3

The hidden state corresponding to the [CLS] token at the final BERT layer is extracted as a fixed-length vector representing the entire input sequence. This pooled representation captures the overall meaning of the text.

4

A linear classification head, a weight matrix and a bias, maps the [CLS] vector to a score per class. A softmax function converts these scores to class probabilities, and the class with the highest probability is the prediction.

Formula
\hat{y} = \text{softmax}(W h_{\texttt{[CLS]}} + b)
5

The full model, BERT layers and classification head together, is optimised on the labelled training set using cross-entropy loss. A small learning rate is used, typically in the 2e-5 to 5e-5 range with AdamW, for a small number of epochs. A learning-rate warm-up schedule limits large early gradient updates that could damage the pre-trained weights.

Common pitfalls

  • Setting the fine-tuning learning rate too high can overwrite the pre-trained weights, so the model fails to improve on a simple baseline. Check validation loss over training before trusting the result.
  • Truncating every input to the first 512 tokens without checking where the informative text sits, for example in a conclusion or closing paragraph of a long document.
  • Evaluating on the data used for training, or tuning hyperparameters against the test set, which inflates the reported performance.
  • Reporting accuracy alone on imbalanced data; the model can score well overall while recall on a minority class is poor.
  • Choosing BERT for a deployment without GPU resources or with strict latency requirements, and discovering only in production that inference is too slow.

Frequently asked questions

How much labelled data do I need to fine-tune BERT?

BERT can yield useful performance with modest labelled datasets, because pre-training has already instilled rich language priors. How much data is enough depends on task difficulty and the number of classes, so there is no fixed threshold. Plot learning curves on a validation set to see whether adding examples still improves performance. With very small per-class sets, overfitting is a real risk, and data augmentation or a lighter model may help.

What learning rate should I use when fine-tuning?

A learning rate between 2e-5 and 5e-5 with the AdamW optimiser is a common starting range for fine-tuning BERT. Higher learning rates tend to overwrite the pre-trained weights; lower ones make convergence very slow. Use a linear warm-up over the first 10% of training steps, and select the final value within the range using the validation set.

My texts are longer than 512 tokens. What should I do?

Common strategies include truncating to the first or last 512 tokens, splitting the document into overlapping chunks and aggregating the [CLS] representations, or using a long-document model such as Longformer or BigBird that can handle sequences of thousands of tokens.

Should I use BERT-base or BERT-large?

BERT-base (110 M parameters) is the practical default: it trains faster, uses less GPU memory, and its accuracy is sufficient for most classification tasks. BERT-large (340 M parameters) can add a few percentage points on complex tasks but requires substantially more compute and is more prone to overfitting on smaller datasets.

How do I evaluate the classifier fairly?

Split data into train, validation, and test sets before any fine-tuning. Report macro F1 (not just accuracy) so that minority-class performance is visible. Use the validation set for hyperparameter search and early stopping, and report the test set result only once at the end.

Related methods

Sources

  1. Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. In Proceedings of NAACL-HLT 2019 (pp. 4171–4186). Association for Computational Linguistics.

    Open DOI reference
  2. Sun, C., Qiu, X., Xu, Y., & Huang, X. (2019). How to Fine-Tune BERT for Text Classification? In China National Conference on Chinese Computational Linguistics (CCL 2019), Lecture Notes in Computer Science, vol 11856, pp. 194–206. Springer.

    Open DOI reference