欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

pytorch_detach 切斷網(wǎng)絡(luò)反傳方式

 更新時(shí)間:2021年05月12日 09:16:33   作者:JJunQw  
這篇文章主要介紹了pytorch_detach 切斷網(wǎng)絡(luò)反傳方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

detach

官方文檔中,對(duì)這個(gè)方法是這么介紹的。

    detach = _add_docstr(_C._TensorBase.detach, r"""
    Returns a new Tensor, detached from the current graph.
    The result will never require gradient.
    .. note::
      Returned Tensor uses the same data tensor as the original one.
      In-place modifications on either of them will be seen, and may trigger
      errors in correctness checks.
    """)

返回一個(gè)新的從當(dāng)前圖中分離的 Variable。

返回的 Variable 永遠(yuǎn)不會(huì)需要梯度

如果 被 detach 的Variable volatile=True, 那么 detach 出來(lái)的 volatile 也為 True

還有一個(gè)注意事項(xiàng),即:返回的 Variable 和 被 detach 的Variable 指向同一個(gè) tensor

import torch
from torch.nn import init
t1 = torch.tensor([1., 2.],requires_grad=True)
t2 = torch.tensor([2., 3.],requires_grad=True)
v3 = t1 + t2
v3_detached = v3.detach()
v3_detached.data.add_(t1) # 修改了 v3_detached Variable中 tensor 的值
print(v3, v3_detached)    # v3 中tensor 的值也會(huì)改變
print(v3.requires_grad,v3_detached.requires_grad)
'''
tensor([4., 7.], grad_fn=<AddBackward0>) tensor([4., 7.])
True False
'''

在pytorch中通過(guò)拷貝需要切斷位置前的tensor實(shí)現(xiàn)這個(gè)功能。tensor中拷貝的函數(shù)有兩個(gè),一個(gè)是clone(),另外一個(gè)是copy_(),clone()相當(dāng)于完全復(fù)制了之前的tensor,他的梯度也會(huì)復(fù)制,而且在反向傳播時(shí),克隆的樣本和結(jié)果是等價(jià)的,可以簡(jiǎn)單的理解為clone只是給了同一個(gè)tensor不同的代號(hào),和‘='等價(jià)。所以如果想要生成一個(gè)新的分開(kāi)的tensor,請(qǐng)使用copy_()。

不過(guò)對(duì)于這樣的操作,pytorch中有專(zhuān)門(mén)的函數(shù)——detach()。

用戶(hù)自己創(chuàng)建的節(jié)點(diǎn)是leaf_node(如圖中的abc三個(gè)節(jié)點(diǎn)),不依賴(lài)于其他變量,對(duì)于leaf_node不能進(jìn)行in_place操作.根節(jié)點(diǎn)是計(jì)算圖的最終目標(biāo)(如圖y),通過(guò)鏈?zhǔn)椒▌t可以計(jì)算出所有節(jié)點(diǎn)相對(duì)于根節(jié)點(diǎn)的梯度值.這一過(guò)程通過(guò)調(diào)用root.backward()就可以實(shí)現(xiàn).

因此,detach所做的就是,重新聲明一個(gè)變量,指向原變量的存放位置,但是requires_grad為false.更深入一點(diǎn)的理解是,計(jì)算圖從detach過(guò)的變量這里就斷了, 它變成了一個(gè)leaf_node.即使之后重新將它的requires_node置為true,它也不會(huì)具有梯度.

pytorch 梯度

(0.4之后),tensor和variable合并,tensor具有g(shù)rad、grad_fn等屬性;

默認(rèn)創(chuàng)建的tensor,grad默認(rèn)為False, 如果當(dāng)前tensor_grad為None,則不會(huì)向前傳播,如果有其它支路具有g(shù)rad,則只傳播其它支路的grad

# 默認(rèn)創(chuàng)建requires_grad = False的Tensor
x = torch.ones(1)   # create a tensor with requires_grad=False (default)
print(x.requires_grad)
 # out: False
 
 # 創(chuàng)建另一個(gè)Tensor,同樣requires_grad = False
y = torch.ones(1)  # another tensor with requires_grad=False
 # both inputs have requires_grad=False. so does the output
z = x + y
 # 因?yàn)閮蓚€(gè)Tensor x,y,requires_grad=False.都無(wú)法實(shí)現(xiàn)自動(dòng)微分,
 # 所以操作(operation)z=x+y后的z也是無(wú)法自動(dòng)微分,requires_grad=False
print(z.requires_grad)
 # out: False
 
 # then autograd won't track this computation. let's verify!
 # 因而無(wú)法autograd,程序報(bào)錯(cuò)
# z.backward()
 # out:程序報(bào)錯(cuò):RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
    
# now create a tensor with requires_grad=True
w = torch.ones(1, requires_grad=True)
print(w.requires_grad)
 # out: True
 
 # add to the previous result that has require_grad=False
 # 因?yàn)閠otal的操作中輸入Tensor w的requires_grad=True,因而操作可以進(jìn)行反向傳播和自動(dòng)求導(dǎo)。
total = w + z
# the total sum now requires grad!
total.requires_grad
# out: True
# autograd can compute the gradients as well
total.backward()
print(w.grad)
#out: tensor([ 1.])
# and no computation is wasted to compute gradients for x, y and z, which don't require grad
# 由于z,x,y的requires_grad=False,所以并沒(méi)有計(jì)算三者的梯度
z.grad == x.grad == y.grad == None
# True

nn.Paramter

import torch.nn.functional as F
# With square kernels and equal stride
filters = torch.randn(8,4,3,3)
weiths = torch.nn.Parameter(torch.randn(8,4,3,3))
inputs = torch.randn(1,4,5,5)
out = F.conv2d(inputs, weiths, stride=2,padding=1)
print(out.shape)
con2d = torch.nn.Conv2d(4,8,3,stride=2,padding=1)
out_2 = con2d(inputs)
print(out_2.shape)

補(bǔ)充:Pytorch-detach()用法

目的:

神經(jīng)網(wǎng)絡(luò)的訓(xùn)練有時(shí)候可能希望保持一部分的網(wǎng)絡(luò)參數(shù)不變,只對(duì)其中一部分的參數(shù)進(jìn)行調(diào)整。

或者訓(xùn)練部分分支網(wǎng)絡(luò),并不讓其梯度對(duì)主網(wǎng)絡(luò)的梯度造成影響.這時(shí)候我們就需要使用detach()函數(shù)來(lái)切斷一些分支的反向傳播.

1 tensor.detach()

返回一個(gè)新的tensor,從當(dāng)前計(jì)算圖中分離下來(lái)。但是仍指向原變量的存放位置,不同之處只是requirse_grad為false.得到的這個(gè)tensir永遠(yuǎn)不需要計(jì)算器梯度,不具有g(shù)rad.

即使之后重新將它的requires_grad置為true,它也不會(huì)具有梯度grad.這樣我們就會(huì)繼續(xù)使用這個(gè)新的tensor進(jìn)行計(jì)算,后面當(dāng)我們進(jìn)行反向傳播時(shí),到該調(diào)用detach()的tensor就會(huì)停止,不能再繼續(xù)向前進(jìn)行傳播.

注意:

使用detach返回的tensor和原始的tensor共同一個(gè)內(nèi)存,即一個(gè)修改另一個(gè)也會(huì)跟著改變。

比如正常的例子是:

import torch 
a = torch.tensor([1, 2, 3.], requires_grad=True)
print(a)
print(a.grad)
out = a.sigmoid()
 
out.sum().backward()
print(a.grad)

輸出

tensor([1., 2., 3.], requires_grad=True)

None

tensor([0.1966, 0.1050, 0.0452])

1.1 當(dāng)使用detach()分離tensor但是沒(méi)有更改這個(gè)tensor時(shí),并不會(huì)影響backward():

import torch 
a = torch.tensor([1, 2, 3.], requires_grad=True)
print(a.grad)
out = a.sigmoid()
print(out)
 
#添加detach(),c的requires_grad為False
c = out.detach()
print(c)
 
#這時(shí)候沒(méi)有對(duì)c進(jìn)行更改,所以并不會(huì)影響backward()
out.sum().backward()
print(a.grad)
 
'''返回:
None
tensor([0.7311, 0.8808, 0.9526], grad_fn=<SigmoidBackward>)
tensor([0.7311, 0.8808, 0.9526])
tensor([0.1966, 0.1050, 0.0452])
'''

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

相關(guān)文章

  • PyQt5 實(shí)現(xiàn)字體大小自適應(yīng)分辨率的方法

    PyQt5 實(shí)現(xiàn)字體大小自適應(yīng)分辨率的方法

    今天小編就為大家分享一篇PyQt5 實(shí)現(xiàn)字體大小自適應(yīng)分辨率的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-06-06
  • 如何搜索查找并解決Django相關(guān)的問(wèn)題

    如何搜索查找并解決Django相關(guān)的問(wèn)題

    每個(gè)程序員都會(huì)在開(kāi)發(fā)過(guò)程中遇到這樣或那樣的問(wèn)題, 有時(shí)光靠一個(gè)人是無(wú)法解決所有問(wèn)題的, 所以我們應(yīng)該找到適當(dāng)?shù)牡胤教釂?wèn).
    2014-06-06
  • python連接mysql有哪些方法

    python連接mysql有哪些方法

    在本篇文章里小編給大家分享的是一篇關(guān)于python連接mysql的方法,有興趣的朋友們可以學(xué)習(xí)下。
    2020-06-06
  • PyCharm在win10的64位系統(tǒng)安裝實(shí)例

    PyCharm在win10的64位系統(tǒng)安裝實(shí)例

    給大家介紹一下在win10的64位系統(tǒng)中安裝PyCharm的操作過(guò)程以及需要注意的地方。
    2017-11-11
  • python?pyaudio音頻錄制的實(shí)現(xiàn)

    python?pyaudio音頻錄制的實(shí)現(xiàn)

    這篇文章主要介紹了python?pyaudio音頻錄制的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • Python語(yǔ)法分析之字符串格式化

    Python語(yǔ)法分析之字符串格式化

    這篇文章主要給大家介紹了關(guān)于Python語(yǔ)法分析之字符串格式化的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Python具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-06-06
  • Python中往列表中插入字典時(shí),數(shù)據(jù)重復(fù)問(wèn)題

    Python中往列表中插入字典時(shí),數(shù)據(jù)重復(fù)問(wèn)題

    這篇文章主要介紹了Python中往列表中插入字典時(shí),數(shù)據(jù)重復(fù)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • Python的經(jīng)緯度與xy坐標(biāo)系相互轉(zhuǎn)換方式

    Python的經(jīng)緯度與xy坐標(biāo)系相互轉(zhuǎn)換方式

    這篇文章主要介紹了Python的經(jīng)緯度與xy坐標(biāo)系相互轉(zhuǎn)換方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • Python?matplotlib可視化之繪制韋恩圖

    Python?matplotlib可視化之繪制韋恩圖

    韋恩圖可以清晰的反映不同組數(shù)據(jù)共有和各自獨(dú)有的部分,本文將詳細(xì)為大家介紹如下兩種python繪制venn圖策略:matplotlib_venn和pyvenn,需要的可以參考一下
    2022-02-02
  • pandas中提取DataFrame某些列的一些方法

    pandas中提取DataFrame某些列的一些方法

    dataframe是pandas包的重要對(duì)象,熟練掌握dataframe的基本操作是很有必要的,下面這篇文章主要給大家介紹了關(guān)于pandas中提取DataFrame某些列的一些方法,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-06-06

最新評(píng)論