pytorch-deep-learning
pytorch-deep-learning copied to clipboard
PyTorch and numpy - when converting from tensor to numpy they are mapped to same memory location
trafficstars
for pytorch version:'1.11.0'
# converting from tensor to numpy
t = torch.ones(7)
np_array = t.numpy()
t , t.dtype , np_array , np_array.dtype
output:
(tensor([1., 1., 1., 1., 1., 1., 1.]),
torch.float32,
array([1., 1., 1., 1., 1., 1., 1.], dtype=float32),
dtype('float32'))
After changing the tensor
# change the tensor see what happens to the numpy array
t += 10
t , t.dtype , np_array , np_array.dtype
output:
(tensor([11., 11., 11., 11., 11., 11., 11.]),
torch.float32,
array([11., 11., 11., 11., 11., 11., 11.], dtype=float32),
dtype('float32'))
according to the TORCH.FROM_NUMPY document(v1.12):
The returned tensor and ndarray share the same memory. Modifications to the tensor will be reflected in the ndarray and vice versa.