Reputation: 313
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 .
Upvotes: 1
Views: 936
Reputation: 23306
You want Tensor.item()
>>> import torch
>>> t = torch.tensor([0])
>>> t.item()
0
If you want to convert it to a letter from A
to Z
you can use:
>>> import string
>>> string.ascii_uppercase[t.item()]
'A'
Be careful to check the shape before doing this, or wrap in a try/except for a possible ValueError
:
>>> t = torch.tensor([0, 1])
>>> t.item()
Traceback (most recent call last):
File "<ipython-input-6-dc80242434c0>", line 1, in <module>
t.item()
ValueError: only one element tensors can be converted to Python scalars
Upvotes: 1
Reputation: 114816
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()]
Upvotes: 1