python - 如何将 torch.Tensor 替换为 python 中的值

标签 python nlp pytorch lookup-tables

我在 pytorch 中的预测是 torch([0]) , torch([1])....,torch([25])分别对应 26 个字母,即 A,B,C....Z .
我的预测以我想要的火炬([0])的形式出现,依此类推。
知道如何进行这种转换。

最佳答案

要将字母表的索引转换为实际字母,您可以:

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)
输出将类似于:
'KEFOTIJBNTAPWHSBXUIQKTTJNSCNDF'

这也适用于 pred使用单个元素,在这种情况下,转换可以更紧凑地完成:
alphabet[pred.item()]

关于python - 如何将 torch.Tensor 替换为 python 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68573682/

相关文章:

pytorch - 如何防止 Pytorch 中张量的某些元素进行梯度计算

python - 尝试将字符串数组转换为具有混合给定数据类型的数组时出现 ValueError

python - 一个好的多线程 python 网络服务器?

python - 具有 1 个序列特征和 3 个当前特征的 LSTM

machine-learning - Mallet 训练模型负载

python - pytorch 如何计算简单线性回归模型的梯度?

python - mongoengine.fields.配置不当 : PIL library was not found

nlp - 如何使用 HuggingFace 将中文翻译成英文?

python - 使用 gensim 从 fasttext 库中高效地加载预训练词嵌入的内存

python-3.x - 运行时错误 : The size of tensor a (133) must match the size of tensor b (10) at non-singleton dimension 1