Search code examples
pythonnlppytorchlookup-tables

how to replace torch.Tensor to a value in python


my predictions in a pytorch are coming as torch([0]) , torch([1])....,torch([25]) for respective 26 alphabets i.e. A,B,C....Z. my prediction are coming as torch([0]) which i want as A and so on . Any idea how to do this conversion .


Solution

  • To convert indices of the alphabet to the actual letters, you can:

    alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'  # the Alphabet
    pred = torch.randint(0, 26, (30,))  # your prediction, int tensor with values in range[0, 25]
    # convert to characters
    pred_string = ''.join(alphabet[c_] for c_ in pred)
    

    the output would be something like:

    'KEFOTIJBNTAPWHSBXUIQKTTJNSCNDF'
    

    This will also work for pred with a single element, in which case the conversion can done more compactly:

    alphabet[pred.item()]