如果变量不再需要,请原地运算

使用​​a+=b​

代码如下所示

import torch as t
a = t.ones(3)
print(a)
print(id(a))
b = t.tensor([1,2,3])
print(b)
a+=b
print(id(a))

pytorch 中如何减少内存占用?_参考资料

使用 ​​a=a+b​

import torch as t
a = t.ones(3)
print(a)
print(id(a))
b = t.tensor([1,2,3])
print(b)
a = a+b
print(id(a))

pytorch 中如何减少内存占用?_深度学习_02

参考资料

  • https://zh-v2.d2l.ai/chapter_preliminaries/ndarray.html#id6 《动手学深度学习v2.0》