When we do conversion from tensor to numpy array via .numpy()
method is it true that tensor and numpy array share the same storage?
OK, but do we check this via code? I would like to prove this since I don’t trust documents in general.
You can for example run
>>> import torch
>>> tensor = torch.arange(6)
>>> array = tensor.numpy()
>>> tensor
tensor([0, 1, 2, 3, 4, 5])
>>> array
array([0, 1, 2, 3, 4, 5])
>>> tensor[0] = 10
>>> tensor
tensor([10, 1, 2, 3, 4, 5])
>>> array
array([10, 1, 2, 3, 4, 5])
>>> array[1] = -2
>>> tensor
tensor([10, -2, 2, 3, 4, 5])
>>> array
array([10, -2, 2, 3, 4, 5])
You can clearly see that both tensor
and array
share storage.
1 Like