![](/img/trans.png)
[英]How to convert TensorFlow tensor to PyTorch tensor without converting to Numpy array?
[英]How to convert a pytorch tensor into a numpy array?
我有一个火炬张量
a = torch.randn(1, 2, 3, 4, 5)
我怎样才能在 numpy 中得到它?
就像是
b = a.tonumpy()
输出应该和我一样
b = np.random.randn(1, 2, 3, 4, 5)
复制自pytorch 文档:
a = torch.ones(5)
print(a)
张量([1., 1., 1., 1., 1.])
b = a.numpy()
print(b)
[1. 1. 1. 1. 1.]
以下与@John 的讨论:
如果张量在(或可以)在 GPU 上,或者如果它(或可以)需要 grad,可以使用
t.detach().cpu().numpy()
我建议仅根据需要丑化您的代码。
您可以尝试以下方法
1. torch.Tensor().numpy()
2. torch.Tensor().cpu().data.numpy()
3. torch.Tensor().cpu().detach().numpy()
另一种有用的方法:
a = torch(0.1, device='cuda')
a.cpu().data.numpy()
回答
数组(0.1,dtype=float32)
这是fastai core 的一个函数:
def to_np(x):
"Convert a tensor to a numpy array."
return apply(lambda o: o.data.cpu().numpy(), x)
可能使用来自预期 PyTorch 库的函数是一个不错的选择。
如果您查看PyTorch Transformers内部,您会发现以下代码:
preds = logits.detach().cpu().numpy()
所以你可能会问为什么需要detach()
方法? 当我们想从 AD 计算图中分离张量时需要它。
还是要注意,CPU张量和numpy数组是相连的。 它们共享相同的存储:
import torch
tensor = torch.zeros(2)
numpy_array = tensor.numpy()
print('Before edit:')
print(tensor)
print(numpy_array)
tensor[0] = 10
print()
print('After edit:')
print('Tensor:', tensor)
print('Numpy array:', numpy_array)
输出:
Before edit:
tensor([0., 0.])
[0. 0.]
After edit:
Tensor: tensor([10., 0.])
Numpy array: [10. 0.]
第一个元素的值由张量和 numpy 数组共享。 在张量中将其更改为 10 也会在 numpy 数组中更改它。
这就是为什么我们需要小心,因为改变 numpy 数组也会改变 CPU 张量。
您可能会发现以下两个函数很有用。
有时候,如果有“应用”渐变,你首先得把.detach()
的函数之前.numpy()
函数。
loss = loss_fn(preds, labels)
print(loss.detach().numpy())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.