How to implement CRF in tensorflow 2
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
A Conditional Random Field is useful for sequence labeling tasks where neighboring tags influence each other, such as named entity recognition or part-of-speech tagging. In TensorFlow 2, a practical approach is to let a neural network produce token-level scores and then train and decode those scores with the CRF utilities from TensorFlow Addons.
Why Add a CRF Layer
A plain softmax classifier predicts each token independently. That is often good enough, but it can produce inconsistent label sequences. For example, a tagging scheme may allow I-PER only after B-PER, yet an independent classifier can still output invalid transitions.
A CRF learns transition scores between labels and decodes the best global path. That usually improves sequence consistency even when the encoder is unchanged.
Model Structure
A common TensorFlow 2 setup looks like this:
- embedding layer
- sequence encoder such as BiLSTM
- dense layer producing emission logits
- CRF log-likelihood for training
- Viterbi decode for inference
The neural network predicts emission scores for each token and tag. The CRF adds transition scores between successive tags.
Minimal TensorFlow 2 Example
The model below produces emission logits. The CRF transition matrix is stored separately so it can be passed to the Addons functions.
The output shape is batch size by sequence length by number of tags. Those are the emission scores consumed by the CRF functions.
Compute Sequence Lengths and Loss
Padding is common in sequence batches, so CRF training also needs the true sequence lengths:
This training step uses tfa.text.crf_log_likelihood, which is the core operation for linear-chain CRF training in TensorFlow Addons.
Decoding with Viterbi
During inference, you want the highest-scoring tag sequence, not just the per-token argmax. Use crf_decode:
The returned tag IDs represent the globally best path under the learned transition rules.
End-to-End Dummy Run
This small example shows the pieces working together on synthetic data:
For a real project, replace the dummy tensors with tokenized inputs, gold label IDs, and a proper training loop.
Common Pitfalls
The biggest issue is mishandling sequence lengths. If padded positions are counted as real tokens, the CRF will learn on garbage transitions and both loss and decoding quality will suffer.
Another common mistake is using plain argmax at inference time. That ignores the CRF transition matrix and defeats the main reason for adding a CRF in the first place.
Masking can also be subtle. mask_zero=True helps the embedding layer, but the CRF functions still need explicit sequence lengths.
Finally, check your dependency strategy. TensorFlow Addons still exposes CRF APIs, but it is a separate package from core TensorFlow, so compatibility should be verified in your environment before you build around it.
Summary
- A CRF is useful when label transitions matter across a sequence.
- In TensorFlow 2, a common pattern is encoder logits plus
tfa.text.crf_log_likelihoodandtfa.text.crf_decode. - The model predicts emission scores, while the CRF learns transition scores between labels.
- Correct sequence lengths are essential for padded batches.
- Use Viterbi decoding at inference time or you lose the structured prediction benefit of the CRF.
Related reading
- how to implement early stopping in tensorflow
- How to implement pixel-wise classification for scene labeling in TensorFlow?
- How to implement PReLU activation in Tensorflow?
- How to implement sklearn's PolynomialFeatures in tensorflow?
- How to implement dropout in Pytorch, and where to apply it
- How to implement Grad-CAM on a trained network
- How to implement Tensorflow batch normalization in LSTM
- How to implement tensorflow Estimator with multiple models for GAN?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.