如何将pytorch张量转换为numpy数组?

Gul*_*zar 20 python numpy pytorch

我有一个火炬张量

a = torch.randn(1, 2, 3, 4, 5)
Run Code Online (Sandbox Code Playgroud)

我怎样才能在 numpy 中得到它?

就像是

b = a.tonumpy()
Run Code Online (Sandbox Code Playgroud)

输出应该和我一样

b = np.random.randn(1, 2, 3, 4, 5)
Run Code Online (Sandbox Code Playgroud)

Gul*_*zar 31

复制自pytorch 文档

a = torch.ones(5)
print(a)
Run Code Online (Sandbox Code Playgroud)

张量([1., 1., 1., 1., 1.])

b = a.numpy()
print(b)
Run Code Online (Sandbox Code Playgroud)

[1. 1. 1. 1. 1.]


以下与@John 的讨论:

如果张量是(或可以是)在 GPU 上,或者如果它(或它可以)需要 grad,可以使用

t.detach().cpu().numpy()

我建议仅根据需要丑化您的代码。


Ash*_*ran 8

您可以尝试以下方法

1. torch.Tensor().numpy()
2. torch.Tensor().cpu().data.numpy()
3. torch.Tensor().cpu().detach().numpy()
Run Code Online (Sandbox Code Playgroud)


Eys*_*ika 5

另一种有用的方法:

a = torch(0.1, device='cuda')

a.cpu().data.numpy()
Run Code Online (Sandbox Code Playgroud)

回答

数组(0.1,dtype=float32)