Pytorch's in-place problem (the difference between a+=b and a=a+b)

import torch

def f_1(mu):
    eps = 0.01
    mu = mu + eps  # 相当于创建了新的变量,原变量没有变
    
    
def f_2(mu):
    eps = 0.01
    mu += eps  # 没有创建新的变量,对原变量进行操作,也就是in-place
    
mu = torch.ones(2, 4)

f_1(mu)
print(mu)
f_2(mu)
print(mu)

'''
tensor([[1., 1., 1., 1.],
        [1., 1., 1., 1.]])
tensor([[1.0100, 1.0100, 1.0100, 1.0100],
        [1.0100, 1.0100, 1.0100, 1.0100]])

'''

Guess you like

Origin blog.csdn.net/mch2869253130/article/details/120028680