Skip to main content
This is a pre-production deployment of Warehouse. Changes made here affect the production instance of PyPI (
Help us improve Python packaging - Donate today!

Conditional random field in PyTorch

Project Description

Conditional random field in PyTorch.


This package provides an implementation of conditional random field (CRF) in PyTorch. This implementation borrows mostly from AllenNLP CRF module with some modifications.


  • Python 3.6
  • PyTorch 0.3.0


You can install with pip

pip install pytorch-crf

Or, you can install from Github directly

pip install git+


In the examples below, we will assume that these lines have been executed

>>> import torch
>>> from torchcrf import CRF
>>> seq_length, batch_size, num_tags = 3, 2, 5
>>> emissions = torch.autograd.Variable(torch.randn(seq_length, batch_size, num_tags), requires_grad=True)
>>> tags = torch.autograd.Variable(torch.LongTensor([[0, 1], [2, 4], [3, 1]]))  # (seq_length, batch_size)
>>> model = CRF(num_tags)

Computing log likelihood

>>> model(emissions, tags)
Variable containing:
[torch.FloatTensor of size 1]

Computing log likelihood with mask

>>> mask = torch.autograd.Variable(torch.ByteTensor([[1, 1], [1, 1], [1, 0]]))  # (seq_length, batch_size)
>>> model(emissions, tags, mask=mask)
Variable containing:
[torch.FloatTensor of size 1]


>>> model.decode(emissions)
[[3, 1, 3], [0, 1, 0]]

Decoding with mask

>>> model.decode(emissions, mask=mask)
[[3, 1, 3], [0, 1, 0]]

See tests/ for more examples.


MIT. See LICENSE for details.


Contributions are welcome! Please follow these instructions to setup dependencies and running the tests and linter. Make a pull request once your contribution is ready.

Installing dependencies

Make sure you setup a virtual environment with Python 3.6 and PyTorch installed. Then, install all the dependencies in requirements.txt file and install this package in development mode.

pip install -r requirements.txt
pip install -e .

Running tests

Run pytest in the project root directory.

Running linter

Run flake8 in the project root directory. This will also run mypy, thanks to flake8-mypy package.

Release History

This version
History Node


History Node


History Node


History Node


History Node


History Node


History Node


History Node


History Node


Download Files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Filename, Size & Hash SHA256 Hash Help File Type Python Version Upload Date
(7.9 kB) Copy SHA256 Hash SHA256
Wheel py3 Jan 4, 2018

Supported By

Elastic Elastic Search Pingdom Pingdom Monitoring Dyn Dyn DNS Sentry Sentry Error Logging CloudAMQP CloudAMQP RabbitMQ Heroku Heroku PaaS Kabu Creative Kabu Creative UX & Design Fastly Fastly CDN DigiCert DigiCert EV Certificate Google Google Cloud Servers