【1】Torch Tensor 转化成 NumPy Array
a = torch.ones(5)
b = a.numpy()    # ★★
# 查看numpy数组的值是如何变化的
a.add_(1)
print(a)
print(b)
【2】NumPy Array 转换成 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)

【3】除了charTensor外,CPU上的所有Tensor都支持转换成NumPy和back        CUDA张量

x = torch.randn(1)
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))

 

转载于:https://www.cnblogs.com/ITCSJ/p/11446390.html

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐