将PyTorch张量转换为python列表

时间:2018-12-23 11:50:35

标签: python pytorch

如何将PyTorch Tensor转换为python列表?

我当前的用例是将大小为[1, 2048, 1, 1]的张量转换为2048个元素的列表。

我的张量具有浮点值。是否有一种解决方案也考虑了int以及其他可能的数据类型?

4 个答案:

答案 0 :(得分:5)

我发现Tensor.tolist()提供了以下用法示例:

>>> a = torch.randn(2, 2)
>>> a.tolist()
[[0.012766935862600803, 0.5415473580360413],
 [-0.08909505605697632, 0.7729271650314331]]
>>> a[0,0].tolist()
0.012766935862600803

因此,要回答此问题,请使用a.squeeze().tolist()删除尺寸为1的所有尺寸。

如果不需要列表,也可以考虑使用.flatten()


在遇到.tolist()之前,我正在使用:

list = [element.item() for element in tensor.flatten()]

这会将张量展平为一个维度,然后调用.item()将每个元素转换为Python数字。

答案 1 :(得分:2)

要列出的张量:

a_list  = embeddings.tolist()

张量列表:

a_tensor = torch.Tensor(a_list).cuda()

答案 2 :(得分:0)

#@pyorch 列表或字符串的张量

in[]
#bbox predictions
boxes = predictions[:, :4]
print(boxes)

out[]

tensor(54.97658) tensor(393.99637) tensor(225.55316) tensor(879.53503)
tensor(670.91669) tensor(400.35202) tensor(810.) tensor(878.34045)
tensor(219.87546) tensor(408.02075) tensor(346.14133) tensor(860.66687)
tensor(13.24882) tensor(217.30855) tensor(800.23413) tensor(737.75751)
tensor(0.12453) tensor(552.29401) tensor(76.41209) tensor(885.35455)
tensor(656.11823) tensor(625.61261) tensor(689.63586) tensor(713.37250)

之后

in[]

boxes = boxes.tolist()
print(boxes)
    
out []
    
54.97657775878906 393.9963684082031 225.55316162109375 879.5350341796875
670.9166870117188 400.3520202636719 810.0 878.3404541015625
219.87545776367188 408.020751953125 346.1413269042969 860.6668701171875
13.24881649017334 217.3085479736328 800.234130859375 737.7575073242188
0.12453281879425049 552.2940063476562 76.4120864868164 885.3545532226562
656.1182250976562 625.6126098632812 689.6358642578125 713.3724975585938

答案 3 :(得分:-2)

尝试reshape

@ManyToMany
@JoinTable(name="TEMPLATE_CONFIGURATIONS",
joinColumns=
    @JoinColumn(name="ID", referencedColumnName="ID"),
inverseJoinColumns=
    @JoinColumn(name="ID", referencedColumnName="ID")
)
private List<Configuration> configurations;

(其中torch.reshape(b, (-1,)) 是您的张量)

相关问题