def __init__(self, ragged: Union[str, _k2.RaggedFloat, _k2.RaggedShape], values: Optional[torch.Tensor] = None): '''Construct an instance of :class:`k2.RaggedFloat`. Args: ragged: It can be one of the following types: - A string. Example value:: [ [1 2] [] [5 10 20] ] - An instance of :class:`_k2.RaggedFloat` - An instance of :class:`_k2.RaggedShape`. In this case, you have to provide the additional argument `values`. values: Required only when `ragged` is an instance of :class:`_k2.RaggedShape`. It is a 1-D torch.Tensor with dtype torch.float32. ''' if isinstance(ragged, str): ragged = _k2.RaggedFloat(ragged) elif isinstance(ragged, _k2.RaggedShape): assert values is not None ragged = _k2.RaggedFloat(ragged, values) assert isinstance(ragged, _k2.RaggedFloat) self.ragged = ragged self._scores = ragged.values()
def test_create_ragged2(self): lst = [[7, 9], [12, 13], []] ragged = k2.create_ragged2(lst) expected = k2.RaggedInt('[[7 9] [12 13] []]') self.assertEqual(str(ragged), str(expected)) float_lst = [[1.2], [], [3.4, 5.6, 7.8]] ragged = k2.create_ragged2(float_lst) expected = _k2.RaggedFloat('[[1.2] [] [3.4 5.6 7.8]]') self.assertEqual(str(ragged), str(expected))
def total_scores(self) -> _k2.RaggedFloat: '''Get total scores of the FSAs in this Nbest. Note: Since FSAs in Nbest are just linear FSAs, log-semirng and tropical semiring produce the same total scores. Returns: Return a ragged tensor with two axes [utt][path_scores]. ''' scores = self.fsa.get_tot_scores(use_double_scores=True, log_semiring=False) # We use single precision here since we only wrap k2.RaggedFloat. # If k2.RaggedDouble is wrapped, we can use double precision here. return _k2.RaggedFloat(self.shape, scores.float())
def test_sum_per_sublist(self): s = ''' 0 1 1 0. 0 1 2 0. 0 1 3 0. 1 2 4 0. 1 2 5 0. 2 3 -1 0. 3 ''' fsa = k2.Fsa.from_str(s) scores = torch.randn_like(fsa.scores) fsa.set_scores_stochastic_(scores) normalized_scores = k2.ragged.sum_per_sublist( _k2.RaggedFloat(fsa.arcs.shape(), fsa.scores.exp())) assert normalized_scores.numel() == fsa.arcs.dim0() assert torch.allclose(normalized_scores[:-1], torch.ones(normalized_scores.numel() - 1)) # the final state has no leaving arcs assert normalized_scores[-1].item() == 0
def __init__(self, ragged: Union[str, _k2.RaggedFloat]): if isinstance(ragged, str): ragged = _k2.RaggedFloat(ragged) self.ragged = ragged self._scores = ragged.values()