How does this work? Why would this assignment affect the original tensor?
aa = torch.tensor([1.,2.,3.])
bb = aa.numpy()
bb[0] = 99.
print(aa[0]) # <--- 99
How does this work? Why would this assignment affect the original tensor?
aa = torch.tensor([1.,2.,3.])
bb = aa.numpy()
bb[0] = 99.
print(aa[0]) # <--- 99
Here’s a reference
https://pytorch.org/docs/stable/generated/torch.Tensor.numpy.html#torch.Tensor.numpy
aa and bb share the memory.
Python uses shallow copying, what you want is a hard copy so changing bb
doesn’t affect aa
. You’ll want to use .clone()
before moving to numpy.
aa = torch.tensor([1.,2.,3.])
bb = aa.clone().numpy() #clone before numpy
bb[0] = 99.
print(aa[0]) # <--- 1
That is very clear! Thank you so much!!