我在“火把”中的预测是以torch([0]) , torch([1])....,torch([25])的形式出现的,分别为26个字母,即A,B,C....Z。我的预言正以火炬()的形式出现,而我想要的是A等等。知道怎么做这个转换吗。
发布于 2021-07-29 09:52:23
要将字母表的索引转换为实际字母,您可以:
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)输出将类似于:
‘’
这也适用于具有单个元素的pred,在这种情况下,转换可以更简洁地完成:
alphabet[pred.item()]发布于 2021-07-29 09:48:30
>>> import torch
>>> t = torch.tensor([0])
>>> t.item()
0如果要将其转换为从A到Z的字母,可以使用:
>>> import string
>>> string.ascii_uppercase[t.item()]
'A'在执行此操作之前,请小心检查形状,或尝试/除了可能的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 scalarshttps://stackoverflow.com/questions/68573682
复制相似问题