Pytorch?nn.Dropout的用法示例詳解
1.nn.Dropout用法一
一句話總結(jié):Dropout的是為了防止過擬合而設(shè)置
詳解部分:
1.Dropout是為了防止過擬合而設(shè)置的
2.Dropout顧名思義有丟掉的意思
3.nn.Dropout(p = 0.3) # 表示每個神經(jīng)元有0.3的可能性不被激活
4.Dropout只能用在訓(xùn)練部分而不能用在測試部分
5.Dropout一般用在全連接神經(jīng)網(wǎng)絡(luò)映射層之后,如代碼的nn.Linear(20, 30)之后

代碼部分:
class Dropout(nn.Module): def __init__(self): super(Dropout, self).__init__() self.linear = nn.Linear(20, 40) self.dropout = nn.Dropout(p = 0.3) # p=0.3表示下圖(a)中的神經(jīng)元有p = 0.3的概率不被激活 def forward(self, inputs): out = self.linear(inputs) out = self.dropout(out) return out net = Dropout() # Dropout只能用在train而不能用在test
2.nn.Dropout用法二
以代碼為例
import torch
import torch.nn as nn
a = torch.randn(4, 4)
print(a)
"""
tensor([[ 1.2615, -0.6423, -0.4142, 1.2982],
[ 0.2615, 1.3260, -1.1333, -1.6835],
[ 0.0370, -1.0904, 0.5964, -0.1530],
[ 1.1799, -0.3718, 1.7287, -1.5651]])
"""
dropout = nn.Dropout()
b = dropout(a)
print(b)
"""
tensor([[ 2.5230, -0.0000, -0.0000, 2.5964],
[ 0.0000, 0.0000, -0.0000, -0.0000],
[ 0.0000, -0.0000, 1.1928, -0.3060],
[ 0.0000, -0.7436, 0.0000, -3.1303]])
"""由以上代碼可知Dropout還可以將部分tensor中的值置為0
補充:torch.nn.dropout和torch.nn.dropout2d的區(qū)別
import torch
import torch.nn as nn
import torch.autograd as autograd
m = nn.Dropout(p=0.5)
n = nn.Dropout2d(p=0.5)
input = autograd.Variable(torch.randn(1, 2, 6, 3)) ## 對dim=1維進行隨機置為0
print(m(input))
print('****************************************************')
print(n(input))
下面的都是錯誤解釋和錯誤示范,沒有刪除的原因是留下來進行對比,希望不要犯這類錯誤
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.autograd as autograd
m = nn.Dropout(p=0.5)
n = nn.Dropout2d(p=0.5)
input = autograd.Variable(torch.randn(2, 6, 3)) ## 對dim=1維進行隨機置為0
print(m(input))
print('****************************************************')
print(n(input))結(jié)果是:

可以看到torch.nn.Dropout對所有元素中每個元素按照概率0.5更改為零, 綠色橢圓,
而torch.nn.Dropout2d是對每個通道按照概率0.5置為0, 紅色方框內(nèi)
注:我只是圈除了部分
到此這篇關(guān)于Pytorch nn.Dropout的用法的文章就介紹到這了,更多相關(guān)Pytorch nn.Dropout用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
pytorch鎖死在dataloader(訓(xùn)練時卡死)
這篇文章主要介紹了pytorch鎖死在dataloader(訓(xùn)練時卡死),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05
利用python的socket發(fā)送http(s)請求方法示例
這篇文章主要給大家介紹了關(guān)于利用python的socket發(fā)送http(s)請求的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用python具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起看看吧2018-05-05

