Why Your PyTorch Tensor Changes When You Edit the NumPy Array
Here is a situation that is easy to run into: you load your data into a NumPy array, convert it to a PyTorch tensor for training, and change a few values in the tensor. Later you print the original array and the changes are already there. You never touched the array.
Or it happens the other way around. You tweak the array, and a tensor you created earlier quietly changes. Nothing crashes and no warning appears, so the bug usually surfaces much later as strange training results.
This article explains what is actually happening, which conversions share memory and which copy, and how to control it.
Quick Summary
- torch.from_numpy() and tensor.numpy() do not copy data. The tensor and the array share the same memory, so an edit on one side shows up on the other.
- torch.tensor() always copies. torch.as_tensor() shares memory only when it doesn't need to change the dtype...
Copyright of this story solely belongs to hackernoon.com. To see the full text click HERE