示例:
x = torch.randn(1)
y1 =x
print("x:",x)
print("y1:",y1)
y2 = x.pow_(2)
print("pow_ ...")
print("x:",x)
print("y1:",y1)
print("y2:",y2)
输出:
x: tensor([-1.7124])
y1: tensor([-1.7124])
pow_ ...
x: tensor([2.9323])
y1: tensor([2.9323])
y2: tensor([2.9323])
结论:
1.pow_()进行了原地操作,由于传递的是引用,x.pow_(2)后,x和y1的值都改变了
2.使用x**2或torch.pow(x,2)代替,不进行原地操作,x和y1不改变