溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何對比pytorch的ReLU和自定義的class GuidedBackpropReLU

發(fā)布時間:2021-12-04 18:43:54 來源:億速云 閱讀:153 作者:柒染 欄目:大數(shù)據(jù)

這篇文章將為大家詳細講解有關(guān)如何對比pytorch的ReLU和自定義的class GuidedBackpropReLU,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

總結(jié)說明:GuidedBackpropReLU和ReLU的區(qū)別很明顯,在反向傳播時候,僅傳播從上一層接受到的正數(shù)梯度,將負數(shù)梯度直接置零.而ReLU則全部接受上一層的梯度,不論該梯度值是正數(shù)還是負數(shù).

實驗代碼展示(實驗中在第58和59行,將coefficient設(shè)置成-1和+1會出現(xiàn)不同的效果):

import torchfrom torch.autograd import Functionclass GuidedBackpropReLU(Function):'''特殊的ReLU,區(qū)別在于反向傳播時候只考慮大于零的輸入和大于零的梯度'''
    # @staticmethod# def forward(ctx, input_img):  # torch.Size([1, 64, 112, 112])#     positive_mask = (input_img > 0).type_as(input_img)  # torch.Size([1, 64, 112, 112])#     # output = torch.addcmul(torch.zeros(input_img.size()).type_as(input_img), input_img, positive_mask)#     output = input_img * positive_mask  # 這行代碼和上一行的功能相同#     ctx.save_for_backward(input_img, output)#     return output  # torch.Size([1, 64, 112, 112])# 上部分定義的函數(shù)功能和以下定義的函數(shù)一致@staticmethoddef forward(ctx, input_img):  # torch.Size([1, 64, 112, 112])output = torch.clamp(input_img, min=0.0)# print('函數(shù)中的輸入張量requires_grad',input_img.requires_grad)ctx.save_for_backward(input_img, output)return output  # torch.Size([1, 64, 112, 112])@staticmethoddef backward(ctx, grad_output):  # torch.Size([1, 2048, 7, 7])input_img, output = ctx.saved_tensors  # torch.Size([1, 2048, 7, 7]) torch.Size([1, 2048, 7, 7])# grad_input = None  # 這行代碼沒作用positive_mask_1 = (input_img > 0).type_as(grad_output)  # torch.Size([1, 2048, 7, 7])  輸入的特征大于零positive_mask_2 = (grad_output > 0).type_as(grad_output)  # torch.Size([1, 2048, 7, 7])  梯度大于零# grad_input = torch.addcmul(#                             torch.zeros(input_img.size()).type_as(input_img),#                             torch.addcmul(#                                             torch.zeros(input_img.size()).type_as(input_img), #                                             grad_output,#                                             positive_mask_1#                             ), #                             positive_mask_2# )grad_input = grad_output * positive_mask_1 * positive_mask_2  # 這行代碼的作用和上一行代碼相同return grad_input


torch.manual_seed(seed=20200910)size = (3,5)input_data_1 = input = torch.randn(*size, requires_grad=True)torch.manual_seed(seed=20200910)input_data_2 = input = torch.randn(*size, requires_grad=True)torch.manual_seed(seed=20200910)input_data_3 = input = torch.randn(*size, requires_grad=True)print('這三個輸入數(shù)據(jù)的維度分別是:', input_data_1.shape, input_data_2.shape, input_data_3.shape)# print(input_data_1)# print(input_data_2)# print(input_data_3)coefficient = -1.0# coefficient = 1.0loss_1 = coefficient * torch.sum(torch.nn.ReLU()(input_data_1))loss_2 = coefficient * torch.sum(torch.nn.functional.relu(input_data_2))loss_3 = coefficient * torch.sum(GuidedBackpropReLU.apply(input_data_3))loss_1.backward()loss_2.backward()loss_3.backward()print(loss_1, loss_2, loss_3)print(loss_1.item(), loss_2.item(), loss_3.item())print('三個損失值是否相等', loss_1.item() == loss_2.item() == loss_3.item())print('簡略打印三個梯度信息...')print(input_data_1.grad)print(input_data_2.grad)print(input_data_3.grad)print('這三個梯度的維度分別是:', input_data_1.grad.shape, input_data_2.grad.shape, input_data_3.grad.shape)print('檢查這三個梯度是否兩兩相等...')print(torch.equal(input_data_1.grad, input_data_2.grad))print(torch.equal(input_data_1.grad, input_data_3.grad))print(torch.equal(input_data_2.grad, input_data_3.grad))

控制臺輸出(#58 coefficient = -1.0):

Windows PowerShell
版權(quán)所有 (C) Microsoft Corporation。保留所有權(quán)利。

嘗試新的跨平臺 PowerShell https://aka.ms/pscore6

加載個人及系統(tǒng)配置文件用了 842 毫秒。
(base) PS C:\Users\chenxuqi\Desktop\News4cxq\test4cxq> conda activate ssd4pytorch2_2_0
(ssd4pytorch2_2_0) PS C:\Users\chenxuqi\Desktop\News4cxq\test4cxq>  & 'D:\Anaconda3\envs\ssd4pytorch2_2_0\python.exe' 'c:\Users\chenxuqi\.vscode\extensions\ms-python.python-2021.1.502429796\pythonFiles\lib\python\debugpy\launcher' '62123' '--' 'c:\Users\chenxuqi\Desktop\News4cxq\test4cxq\testReLU.py'
這三個輸入數(shù)據(jù)的維度分別是: torch.Size([3, 5]) torch.Size([3, 5]) torch.Size([3, 5])
tensor(-7.1553, grad_fn=<MulBackward0>) tensor(-7.1553, grad_fn=<MulBackward0>) tensor(-7.1553, grad_fn=<MulBackward0>)      
-7.155285835266113 -7.155285835266113 -7.155285835266113
三個損失值是否相等 True
簡略打印三個梯度信息...
tensor([[-1.,  0., -1.,  0.,  0.],
        [-1., -1.,  0., -1., -1.],
        [-1., -1.,  0.,  0.,  0.]])
tensor([[-1.,  0., -1.,  0.,  0.],
        [-1., -1.,  0., -1., -1.],
        [-1., -1.,  0.,  0.,  0.]])
tensor([[-0., -0., -0., -0., -0.],
        [-0., -0., -0., -0., -0.],
        [-0., -0., -0., -0., -0.]])
這三個梯度的維度分別是: torch.Size([3, 5]) torch.Size([3, 5]) torch.Size([3, 5])
檢查這三個梯度是否兩兩相等...
True
False
False
(ssd4pytorch2_2_0) PS C:\Users\chenxuqi\Desktop\News4cxq\test4cxq>

控制臺輸出(#59 coefficient = 1.0):

Windows PowerShell
版權(quán)所有 (C) Microsoft Corporation。保留所有權(quán)利。

嘗試新的跨平臺 PowerShell https://aka.ms/pscore6

加載個人及系統(tǒng)配置文件用了 846 毫秒。
(base) PS C:\Users\chenxuqi\Desktop\News4cxq\test4cxq>  & 'D:\Anaconda3\envs\ssd4pytorch2_2_0\python.exe' 'c:\Users\chenxuqi\.vscode\extensions\ms-python.python-2021.1.502429796\pythonFiles\lib\python\debugpy\launcher' '62135' '--' 'c:\Users\chenxuqi\Desktop\News4cxq\test4cxq\testReLU.py'
這三個輸入數(shù)據(jù)的維度分別是: torch.Size([3, 5]) torch.Size([3, 5]) torch.Size([3, 5])
tensor(7.1553, grad_fn=<MulBackward0>) tensor(7.1553, grad_fn=<MulBackward0>) tensor(7.1553, grad_fn=<MulBackward0>)
7.155285835266113 7.155285835266113 7.155285835266113
三個損失值是否相等 True
簡略打印三個梯度信息...
tensor([[1., 0., 1., 0., 0.],
        [1., 1., 0., 1., 1.],
        [1., 1., 0., 0., 0.]])
tensor([[1., 0., 1., 0., 0.],
        [1., 1., 0., 1., 1.],
        [1., 1., 0., 0., 0.]])
tensor([[1., 0., 1., 0., 0.],
        [1., 1., 0., 1., 1.],
        [1., 1., 0., 0., 0.]])
這三個梯度的維度分別是: torch.Size([3, 5]) torch.Size([3, 5]) torch.Size([3, 5])
檢查這三個梯度是否兩兩相等...
True
True
True
(base) PS C:\Users\chenxuqi\Desktop\News4cxq\test4cxq> conda activate ssd4pytorch2_2_0
(ssd4pytorch2_2_0) PS C:\Users\chenxuqi\Desktop\News4cxq\test4cxq>

關(guān)于如何對比pytorch的ReLU和自定義的class GuidedBackpropReLU就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI