Edu*_*era 2 python machine-learning pytorch tensor
在pytorch中,如果我定义一个单元素张量如下:
>>> import torch
>>> target1 = torch.tensor([5])
Run Code Online (Sandbox Code Playgroud)
我可以像这样提取一个元素的值:
>>> target1.item()
5
Run Code Online (Sandbox Code Playgroud)
我想知道的是,当我的张量定义为:
target2 = torch.tensor([[5], [5], [5], [5]])
Run Code Online (Sandbox Code Playgroud)
是否有某种方法(类似于或不类似于上面的.item())将其所有条目提取到一个列表中,例如:
>>> target2.(something)
[5, 5, 5, 5]
Run Code Online (Sandbox Code Playgroud)
我似乎无法在支持此类操作的文档中找到任何功能。
您可以使用
target2.numpy().ravel() 或者
target2.view(-1).numpy() 或者
target2.view(target2.numel()).numpy()
Out[1]: array([5, 5, 5, 5], dtype=int64)
Run Code Online (Sandbox Code Playgroud)