【发布时间】:2020-11-10 19:31:37
【问题描述】:
我有两个相同的张量列表(大小不同),除了第一个的所有张量都分配给 cuda 设备。例如:
list1=[torch.tensor([0,1,2]).cuda(),torch.tensor([3,4,5,6]).cuda(),torch.tensor([7,8]).cuda()]
>>> list1
[tensor([0, 1, 2], device='cuda:0'), tensor([3, 4, 5, 6], device='cuda:0'), tensor([7, 8], device='cuda:0')]
list2=[torch.tensor([0,1,2]),torch.tensor([3,4,5,6]),torch.tensor([7,8])]
>>> list2
[tensor([0, 1, 2]), tensor([3, 4, 5, 6]), tensor([7, 8])]
我想根据索引数组从列表中提取一些张量,例如:
ind=torch.tensor([0,2])
>>> ind
tensor([0, 2])
所以我的解决方案是这样做:
np.array(list1)[ind]
np.array(list2)[ind]
我的问题是为什么它适用于 cuda 设备上定义的张量的第一个列表,并在第二个列表中给出错误,如下所示:
>>> np.array(list1)[ind]
array([tensor([0, 1, 2], device='cuda:0'),
tensor([7, 8], device='cuda:0')], dtype=object)
>>> np.array(list2)[ind]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: only one element tensors can be converted to Python scalars
编辑: 只是为了澄清,由于张量具有不同的形状,因此不会引发错误。以下示例说明了这一点:
list3=[torch.tensor([1,2,3]).cuda()]
list4=[torch.tensor([1,2,3]).cuda(),torch.tensor([4,5,6]).cuda()]
list5=[torch.tensor([1,2,3])]
list6=[torch.tensor([1,2,3]),torch.tensor([4,5,6])]
结果是:
>>> np.array(list3)
array([tensor([1, 2, 3], device='cuda:0')], dtype=object)
>>> np.array(list4)
array([tensor([1, 2, 3], device='cuda:0'),
tensor([4, 5, 6], device='cuda:0')], dtype=object)
>>> np.array(list5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: only one element tensors can be converted to Python scalars
>>> np.array(list6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: only one element tensors can be converted to Python scalars
【问题讨论】: