Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a constrain_crf option to the SequenceLabelingModel #22

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions adaseq/models/sequence_labeling_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from adaseq.data.constant import PAD_LABEL_ID
from adaseq.metainfo import Models, Pipelines, Tasks
from adaseq.models.base import Model
from adaseq.modules.decoders import CRF, PartialCRF
from adaseq.modules.decoders import CRF, PartialCRF, CRFwithConstraints
from adaseq.modules.dropouts import WordDropout
from adaseq.modules.embedders import Embedder
from adaseq.modules.encoders import Encoder
Expand All @@ -33,6 +33,8 @@ class SequenceLabelingModel(Model):
dropout (float, `optional`): dropout rate, default `0.0`.
word_dropout (bool): if `True`, use `WordDropout`.
use_crf (bool, `optional`): whether to use crf, default `True`.
constrain_crf (bool, `optional`): If `True`, then crf is constrained at decoding time to produce valid sequences of tags,
requires use_crf to be `True`, default `False`.
**kwargs: other arguments
"""

Expand All @@ -52,6 +54,7 @@ def __init__(
mv_interpolation: Optional[float] = 0.5,
partial: Optional[bool] = False,
chunk: Optional[bool] = False,
constrain_crf: Optional[bool] = False,
**kwargs
) -> None:
super().__init__(**kwargs)
Expand Down Expand Up @@ -84,8 +87,14 @@ def __init__(
self.dropout = nn.Dropout(dropout)

self.use_crf = use_crf
self.constrain_crf = constrain_crf
if use_crf:
if partial:
if constrain_crf:
id2label_list = [v for k, v in self.id_to_label.items()]
self.crf = CRFwithConstraints(
id2label_list, batch_first=True, add_constraint=True
)
elif partial:
self.crf = PartialCRF(self.num_labels, batch_first=True)
else:
self.crf = CRF(self.num_labels, batch_first=True)
Expand Down