目錄
class torch.
no_grad
[source]
不能進行梯度計算的上下文管理器。當你確定你不調用Tensor.backward()時,
不能計算梯度對測試來講非常有用。對計算它將減少內存消耗,否則requires_grad=True。在這個模式下,每個計算結果都需要使得requires_grad=False,即使當輸入爲requires_grad=True。當使用enable_grad上下文管理器時這個模式不起作用。這個上下文管理器是線程本地的,對其他線程的計算不起作用。同樣函數作爲一個裝飾器(確保用括號實例化。)。
例:
>>> x = torch.tensor([1], requires_grad=True)
>>> with torch.no_grad():
... y = x * 2
>>> y.requires_grad
False
>>> @torch.no_grad()
... def doubler(x):
... return x * 2
>>> z = doubler(x)
>>> z.requires_grad
False