kmkurn / pytorch-crf

(Linear-chain) Conditional random field in PyTorch.
https://pytorch-crf.readthedocs.io
MIT License
935 stars 151 forks source link

Set some transitions to 0 #63

Closed ValerioNeriGit closed 2 years ago

ValerioNeriGit commented 4 years ago

Hi,

let's say I know for sure that a particular transition is never gonna happen, for example from the label 1 to 2. Is there any way I could force a 0 in the transition matrix?

I understand that the CRF layer is able to figure this out by itself, in fact it's going in the right direction but not enough.

Thank you

kmkurn commented 4 years ago

Hi, you should be able to set some transition scores to large negative numbers directly. For example, if you know transitioning from tag index 0 is impossible then you may do:

crf = CRF(num_tags)
torch.nn.init.constant_(crf.start_transitions[0], -1e9)
torch.nn.init.constant_(crf.transitions[0], -1e9)