from_numpy() automatically inherits input array dtype. On the other hand, torch.Tensor is an alias for torch.FloatTensor.
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
Answer from Viacheslav Kroilov on Stack Overflowfrom_numpy() automatically inherits input array dtype. On the other hand, torch.Tensor is an alias for torch.FloatTensor.
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
The recommended way to build tensors in Pytorch is to use the following two factory functions: torch.tensor and torch.as_tensor.
torch.tensor always copies the data. For example, torch.tensor(x) is equivalent to x.clone().detach().
torch.as_tensor always tries to avoid copies of the data. One of the cases where as_tensor avoids copying the data is if the original data is a numpy array.
Error when converting np.float32 array to torch.cuda.FloatTensor
pytorch - How to convert numpy array(float data) to torch tensor? - Stack Overflow
python - Is torch.float32 different from numpy's float32? - Stack Overflow
EulerDiscreteScheduler.set_timesteps() torch.from_numpy misuse error.
Why does it appear that PyTorch tensors give preference to using default element datatype of float32 instead of float64?
For eg., the default element datatype for torch.tensor()is float32. This is the opposite with numpy arrays where the default element datatype for numpy.array()is float64. Why don’t PyTorch make it consistent with numpy arrays and make the default element datatype as float64?
(Ps. I know I can change the element datatypes in the tensor but it would be more convenient if the default was float64)