On a CPU, is torch.as_tensor(a) the same as torch.from_numpy(a) for a numpy array, a? If not, then why not?
From the docs for torch.as_tensor
if the data is an
ndarrayof the correspondingdtypeand thedeviceis the cpu, no copy will be performed.
From the docs for torch.from_numpy:
The returned tensor and
ndarrayshare the same memory. Modifications to the tensor will be reflected in thendarrayand vice versa.
In both cases, any changes the resulting tensor changes the original numpy array.
a = np.array([[1., 2], [3, 4]])
t1 = torch.as_tensor(a)
t2 = torch.from_numpy(a)
t1[0, 0] = 42.
print(a)
# prints [[42., 2.], [3., 4.]]
t2[1, 1] = 55.
print(a)
# prints [[42., 2.], [3., 55.]]
Also, in both cases, attempting to resize_ the tensor results in an error.