
可以讓節點不進行求梯度,從而節省了內存控件,當神經網絡較大且內存不夠用時,就需要讓梯度為False
代碼:
x = torch.tensor([1.0], requires_grad=True)
with torch.no_grad():
y = x * 2
print(y.requires_grad)
print(x.requires_grad)
輸出:
False
True
在with torch.no_grad()下對變量的操作,均不會讓求梯度為真。