将Python列表转换为PyTorch张量

13

我有一个问题,需要将Python数字列表转换为PyTorch张量:这是我的代码:

caption_feat = [int(x)  if x < 11660  else 3 for x in caption_feat]
打印 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. ......])。你有什么想法吗?

1
这只是科学计数法,数字没问题。然而,您应该使用torch.tensor()来构建张量。 - dedObed
4个回答

12
您可以通过定义 dtype 直接将 Python 的 list 转换为 PyTorch 的 Tensor。例如:
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])

5
如果所有元素都是整数,您可以通过定义 dtype 来创建整数 torch 张量。
>>> 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)

当使用 torch.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

0

0
一个简单的方法是将您的列表转换为numpy数组,指定您想要的dtype并在新数组上调用torch.from_numpy
玩具示例:
some_list = [1, 10, 100, 9999, 99999]
tensor = torch.from_numpy(np.array(some_list, dtype=np.int))

正如其他人所建议的那样,另一个选项是在创建张量时指定类型:

torch.tensor(some_list, dtype=torch.int)

两种方法都应该可以正常工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接