NumPy桥
将Torch Tensor 转换为NumPy数组,反之亦然,均轻而易举。
Torch Tensor 和 NumPy 数组将共享其基础内存位置(如果Torch Tensor在CPU上),并且更改一个将更改另一个。
将 Tensor 张量转换为NumPy数组
a = torch.ones(5) print(a)
得到:
tensor([1., 1., 1., 1., 1.])
b = a.numpy() print(b)
得到:
[1. 1. 1. 1. 1.]
查看numpy数组的值如何变化。
a.add_(1)
print(a)
print(b)
得到:
tensor([2., 2., 2., 2., 2.]) [2. 2. 2. 2. 2.]
将NumPy数组转换为Torch张量
查看更改np数组如何自动更改 Torch Tensor
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)
得到:
[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
除了CharTensor之外,CPU上的所有张量都支持转换为NumPy并返回。
CUDA张量
使用该.to
方法可以将张量移动到任何设备上。
# let us run this cell only if CUDA is available
# We will use ``torch.device`` objects to move tensors in and out of GPU
if torch.cuda.is_available():
device = torch.device("cuda") # a CUDA device object
y = torch.ones_like(x, device=device) # directly create a tensor on GPU
x = x.to(device) # or just use strings ``.to("cuda")``
z = x + y
print(z)
print(z.to("cpu", torch.double)) # ``.to`` can also change dtype together!
得到:
tensor([-1.0408], device='cuda:0')
tensor([-1.0408], dtype=torch.float64)
更多内容请访问:IT源点
注意:本文归作者所有,未经作者允许,不得转载