【Python機器學習】Pytorch總結(一)——Torch Tensor 與 NumPy Array的轉化


【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))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM