How to prevent the initial pytorch variable from changing using a function?
I want to apply a function to the variable x and saved as y. But why the x is also changed? How to prevent it?
import torch
def minus_min(raw):
  for col_i in range(len(raw[0])):
    new=raw
    new[:,col_i] = (raw[:,col_i] - raw[:,col_i].min())
  return new

x=torch.tensor([[0,1,2,3,4],
                [2,3,4,0,8],
                [0,1,2,3,4]])
y=minus_min(x)
print(y)
print(x)

output:
tensor([[0, 0, 0, 3, 0],
        [2, 2, 2, 0, 4],
        [0, 0, 0, 3, 0]])
tensor([[0, 0, 0, 3, 0],
        [2, 2, 2, 0, 4],
        [0, 0, 0, 3, 0]])


Because this assignment:
new[:,col_i] = (raw[:,col_i] - raw[:,col_i].min())

is an in-place operation. Therefore, x and y will share the underlying .data.
The smallest change that would solve this issue would be to make a copy of x inside the function:
def minus_min(raw):
  new = raw.clone()  # &lt;--- here
  for col_i in range(len(raw[0])):
    new[:,col_i] = raw[:,col_i] - raw[:,col_i].min()
  return new

If you want, you can simplify your function (and remove the for loop):
y = x - x.min(dim=0).values

