1. 程式人生 > 其它 >Tensor和NumPy相互轉換

Tensor和NumPy相互轉換

  Tensor 和 NumPy 相互轉換常使用 numpy()from_numpy()。需要注意的是: 這兩個函式所產生的 Tensor 和 NumPy 中的陣列共享相同的記憶體(所以他們之間的轉換很快),改變其中一個時另一個也會改變! Tensor 轉 Numpy 陣列
a = torch.ones(3)
b = a.numpy()
print(a)
print(b)

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

a +=  1
print(a)
print(b)

a = a + 1
print(a)
print(b)

tensor([3., 3., 3.])
[
3. 3. 3.] tensor([4., 4., 4.]) [3. 3. 3.] a = torch.ones(3) b = a.numpy() print(a) print(b) b += 1 print(a) print(b) b = b+1 print(a) print(b) tensor([1., 1., 1.]) [1. 1. 1.] tensor([2., 2., 2.]) [2. 2. 2.] tensor([2., 2., 2.]) [3. 3. 3.]

NumPy 陣列轉 Tensor
import numpy as np
a = np.ones(3)
b 
= torch.from_numpy(a) print(a, b) a += 1 print(a, b) b += 1 print(a, b) [1. 1. 1.] tensor([1., 1., 1.], dtype=torch.float64) [2. 2. 2.] tensor([2., 2., 2.], dtype=torch.float64) [3. 3. 3.] tensor([3., 3., 3.], dtype=torch.float64)

  使用 torch.tensor() 將 NumPy 陣列轉換成 Tensor(不再共享記憶體)
c = torch.tensor(a)
a 
+= 1 print(a, c) [4. 4. 4.] tensor([3., 3., 3.], dtype=torch.float64)

因上求緣,果上努力~~~~ 作者:希望每天漲粉,轉載請註明原文連結:https://www.cnblogs.com/BlairGrowing/p/15427954.html