最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

pytorch 禁止/允許計算局部梯度的操作

 更新時間:2021年05月12日 09:05:31   作者:Answerlzd  
這篇文章主要介紹了pytorch 禁止/允許計算局部梯度的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

一、禁止計算局部梯度

torch.autogard.no_grad: 禁用梯度計算的上下文管理器。

當確定不會調(diào)用Tensor.backward()計算梯度時,設置禁止計算梯度會減少內(nèi)存消耗。如果需要計算梯度設置Tensor.requires_grad=True

兩種禁用方法:

將不用計算梯度的變量放在with torch.no_grad()里

>>> x = torch.tensor([1.], requires_grad=True)
>>> with torch.no_grad():
...   y = x * 2
>>> y.requires_grad
Out[12]:False

使用裝飾器 @torch.no_gard()修飾的函數(shù),在調(diào)用時不允許計算梯度

>>> @torch.no_grad()
... def doubler(x):
...     return x * 2
>>> z = doubler(x)
>>> z.requires_grad
Out[13]:False

二、禁止后允許計算局部梯度

torch.autogard.enable_grad :允許計算梯度的上下文管理器

在一個no_grad上下文中使能梯度計算。在no_grad外部此上下文管理器無影響.

用法和上面類似:

使用with torch.enable_grad()允許計算梯度

>>> x = torch.tensor([1.], requires_grad=True)
>>> with torch.no_grad():
...   with torch.enable_grad():
...     y = x * 2
>>> y.requires_grad
Out[14]:True
 
>>> y.backward()  # 計算梯度
>>> x.grad
Out[15]: tensor([2.])

在禁止計算梯度下調(diào)用被允許計算梯度的函數(shù),結(jié)果可以計算梯度

>>> @torch.enable_grad()
... def doubler(x):
...     return x * 2
 
>>> with torch.no_grad():
...     z = doubler(x)
>>> z.requires_grad
 
Out[16]:True

三、是否計算梯度

torch.autograd.set_grad_enable()

可以作為一個函數(shù)使用:

>>> x = torch.tensor([1.], requires_grad=True)
>>> is_train = False
>>> with torch.set_grad_enabled(is_train):
...   y = x * 2
>>> y.requires_grad
Out[17]:False
 
>>> torch.set_grad_enabled(True)
>>> y = x * 2
>>> y.requires_grad
Out[18]:True
 
>>> torch.set_grad_enabled(False)
>>> y = x * 2
>>> y.requires_grad
Out[19]:False

總結(jié):

單獨使用這三個函數(shù)時沒有什么,但是若是嵌套,遵循就近原則。

x = torch.tensor([1.], requires_grad=True)
 
with torch.enable_grad():
    torch.set_grad_enabled(False)
    y = x * 2
    print(y.requires_grad)
Out[20]: False
 
torch.set_grad_enabled(True)
with torch.no_grad():
    z = x * 2
    print(z.requires_grad)
Out[21]:False

補充:pytorch局部范圍內(nèi)禁用梯度計算,no_grad、enable_grad、set_grad_enabled使用舉例

在這里插入圖片描述 在這里插入圖片描述

原文及翻譯

Locally disabling gradient computation
在局部區(qū)域內(nèi)關(guān)閉(禁用)梯度的計算.
The context managers torch.no_grad(), torch.enable_grad(), 
and torch.set_grad_enabled() are helpful for locally disabling 
and enabling gradient computation. See Locally disabling gradient 
computation for more details on their usage. These context 
managers are thread local, so they won't work if you send 
work to another thread using the threading module, etc.
上下文管理器torch.no_grad()、torch.enable_grad()和
torch.set_grad_enabled()可以用來在局部范圍內(nèi)啟用或禁用梯度計算.
在Locally disabling gradient computation章節(jié)中詳細介紹了
局部禁用梯度計算的使用方式.這些上下文管理器具有線程局部性,
因此,如果你使用threading模塊來將工作負載發(fā)送到另一個線程,
這些上下文管理器將不會起作用.

no_grad   Context-manager that disabled gradient calculation.
no_grad   用于禁用梯度計算的上下文管理器.
enable_grad  Context-manager that enables gradient calculation.
enable_grad  用于啟用梯度計算的上下文管理器.
set_grad_enabled  Context-manager that sets gradient calculation to on or off.
set_grad_enabled  用于設置梯度計算打開或關(guān)閉狀態(tài)的上下文管理器.

例子1

Microsoft Windows [版本 10.0.18363.1440]
(c) 2019 Microsoft Corporation。保留所有權(quán)利。
C:\Users\chenxuqi>conda activate pytorch_1.7.1_cu102
(pytorch_1.7.1_cu102) C:\Users\chenxuqi>python
Python 3.7.9 (default, Aug 31 2020, 17:10:11) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.manual_seed(seed=20200910)
<torch._C.Generator object at 0x000001A2E55A8870>
>>> a = torch.randn(3,4,requires_grad=True)
>>> a
tensor([[ 0.2824, -0.3715,  0.9088, -1.7601],
        [-0.1806,  2.0937,  1.0406, -1.7651],
        [ 1.1216,  0.8440,  0.1783,  0.6859]], requires_grad=True)
>>> b = a * 2
>>> b
tensor([[ 0.5648, -0.7430,  1.8176, -3.5202],
        [-0.3612,  4.1874,  2.0812, -3.5303],
        [ 2.2433,  1.6879,  0.3567,  1.3718]], grad_fn=<MulBackward0>)
>>> b.requires_grad
True
>>> b.grad
__main__:1: UserWarning: The .grad attribute of a Tensor that is not a leaf Tensor is being accessed. Its .grad attribute won't be populated during autograd.backward(). If you indeed want the gradient for a non-leaf Tensor, use .retain_grad() on the non-leaf Tensor. If you access the non-leaf Tensor by mistake, make sure you access the leaf Tensor instead. See github.com/pytorch/pytorch/pull/30531 for more informations.
>>> print(b.grad)
None
>>> a.requires_grad
True
>>> a.grad
>>> print(a.grad)
None
>>>
>>> with torch.no_grad():
...     c = a * 2
...
>>> c
tensor([[ 0.5648, -0.7430,  1.8176, -3.5202],
        [-0.3612,  4.1874,  2.0812, -3.5303],
        [ 2.2433,  1.6879,  0.3567,  1.3718]])
>>> c.requires_grad
False
>>> print(c.grad)
None
>>> a.grad
>>>
>>> print(a.grad)
None
>>> c.sum()
tensor(6.1559)
>>>
>>> c.sum().backward()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\Anaconda3\envs\pytorch_1.7.1_cu102\lib\site-packages\torch\tensor.py", line 221, in backward
    torch.autograd.backward(self, gradient, retain_graph, create_graph)
  File "D:\Anaconda3\envs\pytorch_1.7.1_cu102\lib\site-packages\torch\autograd\__init__.py", line 132, in backward
    allow_unreachable=True)  # allow_unreachable flag
RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
>>>
>>>
>>> b.sum()
tensor(6.1559, grad_fn=<SumBackward0>)
>>> b.sum().backward()
>>>
>>>
>>> a.grad
tensor([[2., 2., 2., 2.],
        [2., 2., 2., 2.],
        [2., 2., 2., 2.]])
>>> a.requires_grad
True
>>>
>>>

例子2

Microsoft Windows [版本 10.0.18363.1440]
(c) 2019 Microsoft Corporation。保留所有權(quán)利。
C:\Users\chenxuqi>conda activate pytorch_1.7.1_cu102
(pytorch_1.7.1_cu102) C:\Users\chenxuqi>python
Python 3.7.9 (default, Aug 31 2020, 17:10:11) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.manual_seed(seed=20200910)
<torch._C.Generator object at 0x000002109ABC8870>
>>>
>>> a = torch.randn(3,4,requires_grad=True)
>>> a
tensor([[ 0.2824, -0.3715,  0.9088, -1.7601],
        [-0.1806,  2.0937,  1.0406, -1.7651],
        [ 1.1216,  0.8440,  0.1783,  0.6859]], requires_grad=True)
>>> a.requires_grad
True
>>>
>>> with torch.set_grad_enabled(False):
...     b = a * 2
...
>>> b
tensor([[ 0.5648, -0.7430,  1.8176, -3.5202],
        [-0.3612,  4.1874,  2.0812, -3.5303],
        [ 2.2433,  1.6879,  0.3567,  1.3718]])
>>> b.requires_grad
False
>>>
>>> with torch.set_grad_enabled(True):
...     c = a * 3
...
>>> c
tensor([[ 0.8472, -1.1145,  2.7263, -5.2804],
        [-0.5418,  6.2810,  3.1219, -5.2954],
        [ 3.3649,  2.5319,  0.5350,  2.0576]], grad_fn=<MulBackward0>)
>>> c.requires_grad
True
>>>
>>> d = a * 4
>>> d.requires_grad
True
>>>
>>> torch.set_grad_enabled(True)  # this can also be used as a function
<torch.autograd.grad_mode.set_grad_enabled object at 0x00000210983982C8>
>>>
>>> # 以函數(shù)調(diào)用的方式來使用
>>>
>>> e = a * 5
>>> e
tensor([[ 1.4119, -1.8574,  4.5439, -8.8006],
        [-0.9030, 10.4684,  5.2031, -8.8257],
        [ 5.6082,  4.2198,  0.8917,  3.4294]], grad_fn=<MulBackward0>)
>>> e.requires_grad
True
>>>
>>> d
tensor([[ 1.1296, -1.4859,  3.6351, -7.0405],
        [-0.7224,  8.3747,  4.1625, -7.0606],
        [ 4.4866,  3.3759,  0.7133,  2.7435]], grad_fn=<MulBackward0>)
>>>
>>> torch.set_grad_enabled(False) # 以函數(shù)調(diào)用的方式來使用
<torch.autograd.grad_mode.set_grad_enabled object at 0x0000021098394C48>
>>>
>>> f = a * 6
>>> f
tensor([[  1.6943,  -2.2289,   5.4527, -10.5607],
        [ -1.0836,  12.5621,   6.2437, -10.5908],
        [  6.7298,   5.0638,   1.0700,   4.1153]])
>>> f.requires_grad
False
>>>
>>>
>>>

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。

相關(guān)文章

  • Pandas實現(xiàn)一列數(shù)據(jù)分隔為兩列

    Pandas實現(xiàn)一列數(shù)據(jù)分隔為兩列

    這篇文章主要介紹了Pandas實現(xiàn)一列數(shù)據(jù)分隔為兩列,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05
  • Python實現(xiàn)的十進制小數(shù)與二進制小數(shù)相互轉(zhuǎn)換功能

    Python實現(xiàn)的十進制小數(shù)與二進制小數(shù)相互轉(zhuǎn)換功能

    這篇文章主要介紹了Python實現(xiàn)的十進制小數(shù)與二進制小數(shù)相互轉(zhuǎn)換功能,結(jié)合具體實例形式詳細分析了二進制與十進制相互轉(zhuǎn)換的原理及Python相關(guān)實現(xiàn)技巧,需要的朋友可以參考下
    2017-10-10
  • PyCharm中如何切換Python版本

    PyCharm中如何切換Python版本

    這篇文章主要介紹了PyCharm中如何切換Python版本問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • 深入探究Python如何實現(xiàn)100個并發(fā)請求

    深入探究Python如何實現(xiàn)100個并發(fā)請求

    在Web開發(fā)和數(shù)據(jù)抓取等領(lǐng)域,并發(fā)請求是提高效率和性能的重要手段,本文將深入探討如何使用Python實現(xiàn)100個并發(fā)請求,感興趣的小伙伴可以了解下
    2025-02-02
  • python-try-except:pass的用法及說明

    python-try-except:pass的用法及說明

    這篇文章主要介紹了python-try-except:pass的用法及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • python保留小數(shù)位的三種實現(xiàn)方法

    python保留小數(shù)位的三種實現(xiàn)方法

    本文給大家分享python保留小數(shù)位的三種方法,代碼簡單易懂,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-01-01
  • 實例講解python讀取各種文件的方法

    實例講解python讀取各種文件的方法

    這篇文章主要為大家詳細介紹了python讀取各種文件的方法,,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-02-02
  • 關(guān)于keras中的Reshape用法

    關(guān)于keras中的Reshape用法

    這篇文章主要介紹了關(guān)于keras中的Reshape用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • python之文件讀取一行一行的方法

    python之文件讀取一行一行的方法

    今天小編就為大家分享一篇python之文件讀取一行一行的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-07-07
  • 聊聊boost?python3依賴安裝問題

    聊聊boost?python3依賴安裝問題

    這篇文章主要介紹了boost?python3依賴安裝,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-12-12

最新評論

梅州市| 双流县| 胶州市| 交口县| 汝阳县| 三门峡市| 辽宁省| 高平市| 平顺县| 偏关县| 会东县| 石屏县| 随州市| 惠水县| 当涂县| 铜陵市| 新宾| 聂拉木县| 栾城县| 潼关县| 天峨县| 嵊州市| 丁青县| 嵊泗县| 普安县| 溧阳市| 中江县| 久治县| 丽江市| 陇西县| 龙南县| 大埔县| 西畴县| 视频| 南汇区| 天峻县| 车致| 闻喜县| 长子县| 同心县| 全州县|