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

GH-3070: Fix inconsistency between best path and scores in ViterbiDecoder #3189

Merged
merged 6 commits into from
Oct 23, 2023
Merged
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
16 changes: 14 additions & 2 deletions flair/models/sequence_tagger_utils/viterbi.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,13 +221,25 @@ def decode(
)

if probabilities_for_all_classes:
all_tags = self._all_scores_for_token(scores.cpu(), lengths, sentences)
all_tags = self._all_scores_for_token(scores.cpu(), tag_seq, lengths, sentences)

return tags, all_tags

def _all_scores_for_token(self, scores: torch.Tensor, lengths: torch.IntTensor, sentences: List[Sentence]):
def _all_scores_for_token(
self, scores: torch.Tensor, tag_seq: torch.IntTensor, lengths: torch.IntTensor, sentences: List[Sentence]
):
"""Returns all scores for each tag in tag dictionary."""
scores = scores.numpy()
for i_batch, batch in enumerate(scores):
for i, (tag_id, tag_scores) in enumerate(zip(tag_seq, batch)):
tag_id_int = tag_id if isinstance(tag_id, int) else int(tag_id.item())

if tag_id_int != np.argmax(tag_scores):
swap_index_score = int(np.argmax(tag_scores))
scores[i_batch][i][tag_id_int], scores[i_batch][i][swap_index_score] = (
scores[i_batch][i][swap_index_score],
scores[i_batch][i][tag_id_int],
)
prob_tags_per_sentence = []
for scores_sentence, length, sentence in zip(scores, lengths, sentences):
scores_sentence = scores_sentence[:length]
Expand Down