"projects/DeepLab/deeplab/config.py" did not exist on "5b3792fc3ef9ab6a6f8f30634ab2e52fb0941af3"
greedy_decoder.py 813 Bytes
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import torch


class Decoder(torch.nn.Module):
    def __init__(self, labels):
        super().__init__()
        self.labels = labels

    def forward(self, logits: torch.Tensor) -> str:
        """Given a sequence logits over labels, get the best path string

        Args:
            logits (Tensor): Logit tensors. Shape `[num_seq, num_label]`.

        Returns:
            str: The resulting transcript
        """
        best_path = torch.argmax(logits, dim=-1)  # [num_seq,]
        best_path = torch.unique_consecutive(best_path, dim=-1)
20
        hypothesis = ""
21
22
        for i in best_path:
            char = self.labels[i]
23
            if char in ["<s>", "<pad>"]:
24
                continue
25
26
            if char == "|":
                char = " "
27
28
            hypothesis += char
        return hypothesis