【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

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐