- Introduced by
- Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (Google AI Language)
- Year
- 2019
- Type
- Pretrain-then-fine-tune transformer model
- Family
- Deep learning / NLP / CV
What does it do?
Self-supervised BERT-based classification fine-tunes BERT, a transformer encoder pretrained on large unlabelled text with masked-language modelling, so that it assigns texts to categories using labelled examples.
A small classification layer is placed on the pretrained encoder and the whole model is trained on the task data. Results depend on the task, the input length, and how closely the text matches the pretraining corpus, so the method is not uniformly superior to simpler baselines.
The intuition behind the method
BERT reads every word in context of all surrounding words simultaneously, unlike older left-to-right models. Before seeing any labels, it learns language representations by predicting masked words in large amounts of unlabelled text, a self-supervised objective that requires no human annotation. Fine-tuning then attaches a small classification layer on top and trains end-to-end on your labelled examples, so the model adapts its general language understanding to your task, which is why it can often work with less labelled data than training from scratch.
History
BERT was introduced by Devlin et al. at Google AI Language and published at NAACL-HLT 2019. Its masked-language-modelling objective, together with the pretrain-then-fine-tune approach, has been widely adopted in NLP, and later variants and domain-specific checkpoints have followed.
When to use it
Choose this method for text classification tasks such as sentiment analysis, topic labelling, intent detection, or natural language inference, especially when labelled data is limited, because pretrained representations reduce how much task-specific data is needed. It works best on well-formed prose in the same language as the pretrained checkpoint. Avoid it when documents regularly exceed the 512-token input limit and no segmentation strategy (such as sliding windows or hierarchical models) is planned. A TF-IDF plus logistic regression baseline is a sensible first choice when compute or latency is tightly constrained and it already performs adequately. Be cautious when the text domain differs strongly from the pretraining corpus, for example in highly specialised clinical codes, unless a domain-adapted checkpoint is available.
Limitations and considerations
- The maximum input length is 512 tokens, so longer documents must be truncated, chunked, or processed with a hierarchical model.
- Inference is slower than lightweight models such as TF-IDF with logistic regression or fastText, which matters in latency-sensitive production settings.
- The base model has about 110M parameters, which makes deployment on edge or embedded devices difficult.
- Gains can shrink when the task vocabulary or writing style differs substantially from the text the model was pretrained on.
Source conditions do not replace independent scientific review or validation by an analysis engine.
Strengths
- The pretrained encoder is reused, and the task-specific addition is a single linear layer on the [CLS] embedding. Fine-tuning still updates all model weights (about 110M in BERT-base), so compute and memory costs are those of full-model training, not of training a small classifier alone.
- Bidirectional context lets the model use words on both sides of a token, which can help with negation and word sense in many tasks, although the size of the gain depends on the dataset.
- Domain-specific checkpoints (BioBERT, SciBERT, ClinicalBERT) are available, which can narrow the gap between the pretraining corpus and specialised text.
- Pretrained weights are publicly available, so the same fine-tuning procedure can be applied to many classification tasks without pretraining from scratch.
Applications
- Sentiment analysis of product reviews, social media posts, and customer feedback.
- Topic and intent classification in dialogue systems and chatbots.
- Natural language inference and textual entailment.
- Spam, toxicity, and hate-speech detection in content moderation.
- Clinical document classification and medical coding with domain-adapted checkpoints (ClinicalBERT, BioBERT).
- News categorisation and scientific abstract classification in academic search.
How it works
How it works
Raw text is segmented into WordPiece tokens, a special [CLS] token is prepended, and a [SEP] token marks sentence boundaries. Each token receives the sum of its token embedding, positional embedding, and segment embedding, producing a fixed-dimensional input vector per token.
During pretraining, roughly 15% of token positions are selected, and the model is trained to recover the original tokens at those positions from the bidirectional context of all other tokens (Masked Language Modelling, MLM). A secondary Next Sentence Prediction (NSP) task trains the model to judge whether two sentences follow each other, which is intended to help with sentence-pair understanding.
Formula
\mathcal{L}_{MLM} = -\sum_{i \in \mathcal{M}} \log P(x_i \mid x_{\setminus i}; \theta)After passing through multiple stacked self-attention transformer blocks, the final hidden state of the [CLS] token serves as a fixed-length sentence-level representation that aggregates information from the entire input sequence via attention over all tokens.
Formula
h_{[CLS]} = \text{BERT}(x)[0]A lightweight linear layer maps the [CLS] embedding to class logits, followed by a softmax to produce class probabilities. This head adds few parameters relative to the pretrained backbone and is trained together with the transformer weights during fine-tuning.
Formula
\hat{y} = \text{softmax}(W \, h_{[CLS]} + b)The full model, consisting of the pretrained transformer and the classification head, is trained end-to-end on labelled examples using cross-entropy loss, so all model weights are updated, not only the head. A low learning rate is the usual choice (commonly 2e-5 to 5e-5) with an Adam-family optimiser. Training for 2–4 epochs is a common starting point; too many epochs on a small dataset risks overfitting and erasing useful pretrained representations. Batch size also affects training stability, especially on small datasets, and is worth tuning together with the learning rate.
Formula
\mathcal{L}_{CE} = -\sum_{c} y_c \log \hat{y}_cCommon pitfalls
- Using too high a learning rate during fine-tuning can overwrite pretrained representations, which is why the learning rate is kept low.
- Relying on accuracy alone under class imbalance can hide poor performance on minority classes; macro-F1 together with per-class precision and recall gives a clearer picture.
- Treating the 512-token limit as a minor issue without checking the token-length distribution of the dataset can silently discard the end of many documents.
- Running many fine-tuning epochs on a small dataset tends to overfit the classification head, and the pretrained layers can drift away from useful general representations.
- Using validation loss alone as the stopping criterion, without a separate held-out test set, gives an optimistic estimate of performance.
Frequently asked questions
How much labelled data do I need to fine-tune BERT for classification?
Fine-tuning can work with relatively small labelled sets in many tasks, and larger labelled sets generally give stronger and more stable results. The amount needed depends on the number of classes, the difficulty of the task, and how closely the text matches the pretraining data. For very small datasets, few-shot or prompt-based approaches are worth considering.
Which BERT checkpoint should I start with?
For general English text, bert-base-uncased is a common default. For scientific or biomedical text, SciBERT or BioBERT reduce the domain gap. For multilingual tasks, mBERT or XLM-RoBERTa cover many languages.
What learning rate and number of epochs are recommended?
A learning rate between 2e-5 and 5e-5 and 2–4 fine-tuning epochs are a standard starting point for BERT fine-tuning. Use early stopping based on validation performance to avoid overfitting on small datasets. Batch size also influences stability and is worth tuning on the validation set.
How do I handle documents longer than 512 tokens?
Common strategies include truncating to the first 512 tokens, using a sliding window with aggregated predictions, or using a hierarchical model over segments. Models designed for longer inputs are an alternative when the document length makes these strategies inadequate.
Is fine-tuned BERT interpretable?
Not directly. Attention weights provide limited interpretability. Techniques such as Integrated Gradients, LIME, or SHAP can produce token-level attribution scores, but these are post-hoc approximations rather than true model explanations.
Sources
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, 4171–4186. Association for Computational Linguistics.
Open DOI referenceSun, 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), LNCS 11856, 194–206. Springer.
Open DOI reference