将 python 列表转换为 pytorch 张量

Ame*_*Ali 14 python pytorch

我在将 python 数字列表转换为 pytorch 张量时遇到问题:这是我的代码:

caption_feat = [int(x)  if x < 11660  else 3 for x in caption_feat]
Run Code Online (Sandbox Code Playgroud)

打印caption_feat给出:[1, 9903, 7876, 9971, 2770, 2435, 10441, 9370, 2]
我像这样进行转换:tmp2 = torch.Tensor(caption_feat) 现在打印tmp2给出:tensor([1.0000e+00, 9.9030e+03, 7.8760e+03, 9.9710e+03, 2.7700e+03, 2.4350e+03, 1.0441e+04, 9.3700e+03, 2.0000e+00])
但是我期望得到:tensor([1. , 9903, , 9971. ......]) 有什么想法吗?

小智 15

您可以通过定义 .py 文件直接将 python 转换list为 pytorch 。例如,Tensordtype

import torch

a_list = [3,23,53,32,53] 
a_tensor = torch.Tensor(a_list)
print(a_tensor.int())

>>> tensor([3,23,53,32,53])
Run Code Online (Sandbox Code Playgroud)


Dis*_*ani 5

如果所有元素都是整数,您可以通过定义来制作整数火炬张量dtype

>>> a_list = [1, 9903, 7876, 9971, 2770, 2435, 10441, 9370, 2]
>>> tmp2 = torch.tensor(a_list, dtype=torch.int)
>>> tmp2
tensor([    1,  9903,  7876,  9971,  2770,  2435, 10441,  9370,     2],
       dtype=torch.int32)
Run Code Online (Sandbox Code Playgroud)

whiletorch.Tensor返回torch.float32使其以科学记数法打印数字

>>> tmp2 = torch.Tensor(a_list)
>>> tmp2
tensor([1.0000e+00, 9.9030e+03, 7.8760e+03, 9.9710e+03, 2.7700e+03, 2.4350e+03,
        1.0441e+04, 9.3700e+03, 2.0000e+00])
>>> tmp2.dtype
torch.float32
Run Code Online (Sandbox Code Playgroud)