一、numpy數組轉化為torch中的tensor:
總的來說有四種方法,如下:
import torch
import numpy as np
arr1 = np.array([1,2,3], dtype=np.float32)
arr2 = np.array([4,5,6])
print(arr1.dtype)
print("nunpy中array的預設資料類型為:", arr2.dtype)
tensor = torch.tensor(arr2)
Tensor = torch.Tensor(arr2)
as_tensor = torch.as_tensor(arr2)
from_numpy = torch.from_numpy(arr2)
print(tensor.dtype, "|",Tensor.dtype, "|",as_tensor.dtype, "|",from_numpy.dtype)
arr2[0] = 10
print(tensor, Tensor, as_tensor, from_numpy)
'''
結果為:
float32
numpy中array的預設資料類型為: int64
torch.int64 | torch.float32 | torch.int64 | torch.int64
tensor([4, 5, 6]) tensor([4., 5., 6.]) tensor([10, 5, 6]) tensor([10, 5, 6])
'''
上述中可以看出來:
- numpy中array預設的資料格式是int64類型,而torch中tensor預設的資料格式是float32類型。
- as_tensor和from_array是淺拷貝,而tensor和Tensor則是屬于深拷貝,淺拷貝是直接共享記憶體記憶體空間的,這樣效率更高,而深拷貝是直接建立一個新的副本。
二、torch中的tensor轉化為numpy數組:
import torch
import numpy as np
a = torch.ones(5)
b = a.numpy()
b[0] = 2
print(a)
print(b)
'''
tensor([2., 1., 1., 1., 1.])
[2. 1. 1. 1. 1.]
'''
從上述的結果看來這個numpy() 方法将tensor轉numpy的array也是記憶體共享的。