pytorch tensor與numpy轉換


從官網拷貝過來的,就是做個學習記錄。版本 0.4


 

tensor to numpy

a = torch.ones(5)
print(a)

輸出

tensor([1., 1., 1., 1., 1.])

進行轉換

b = a.numpy()
print(b)

輸出

[1. 1. 1. 1. 1.]

注意,轉換后的tensor與numpy指向同一地址,所以,對一方的值改變另一方也隨之改變

a.add_(1)
print(a)
print(b)

numpy to 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外所有tensor都可以轉換為numpy


免責聲明!

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



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