且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PyTorch内存模型:对比"torch.Tensor()"

更新时间:2023-12-01 23:33:28

from_numpy()自动继承输入数组dtype.另一方面,torch.Tensortorch.FloatTensor的别名.

from_numpy() automatically inherits input array dtype. On the other hand, torch.Tensor is an alias for torch.FloatTensor.

因此,如果将int64数组传递给torch.Tensor,则输出张量为浮点张量,它们将不会共享存储. torch.from_numpy为您提供了torch.LongTensor的期望.

Therefore, if you pass int64 array to torch.Tensor, output tensor is float tensor and they wouldn't share the storage. torch.from_numpy gives you torch.LongTensor as expected.

a = np.arange(10)
ft = torch.Tensor(a)  # same as torch.FloatTensor
it = torch.from_numpy(a)

a.dtype  # == dtype('int64')
ft.dtype  # == torch.float32
it.dtype  # == torch.int64