Pytorch模型定義與深度學習自查手冊
定義神經(jīng)網(wǎng)絡(luò)
- 繼承nn.Module類;
- 初始化函數(shù)__init__:網(wǎng)絡(luò)層設(shè)計;
- forward函數(shù):模型運行邏輯。
class NeuralNetwork(nn.Module): def __init__(self): super(NeuralNetwork, self).__init__() self.flatten = nn.Flatten() self.linear_relu_stack = nn.Sequential( nn.Linear(28*28, 512), nn.ReLU(), nn.Linear(512, 512), nn.ReLU(), nn.Linear(512, 10), ) def forward(self, x): x = self.flatten(x) logits = self.linear_relu_stack(x) return logits |
權(quán)重初始化
方法1:net.apply(weights_init)
def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find('BatchNorm') != -1: nn.init.normal_(m.weight.data, 1.0, 0.02) nn.init.constant_(m.bias.data, 0) net=Model() net.apply(weights_init) |
方法2:在網(wǎng)絡(luò)初始化的時候進行參數(shù)初始化
- 使用net.modules()遍歷模型中的網(wǎng)絡(luò)層的類型;
- 對其中的m層的weigth.data(tensor)部分進行初始化操作。
class Model(nn.Module): def __init__(self, block, layers, num_classes=1000): self.inplanes = 64 super(Model, self).__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = ... ... # 權(quán)值參數(shù)初始化 for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() |
常用的操作
利用nn.Parameter()設(shè)計新的層
import torch from torch import nn class MyLinear(nn.Module): def __init__(self, in_features, out_features): super().__init__() self.weight = nn.Parameter(torch.randn(in_features, out_features)) self.bias = nn.Parameter(torch.randn(out_features)) def forward(self, input): return (input @ self.weight) + self.bias |
nn.Flatten
展平輸入的張量: 28x28 -> 784
input = torch.randn(32, 1, 5, 5) m = nn.Sequential( nn.Conv2d(1, 32, 5, 1, 1), nn.Flatten() ) output = m(input) output.size() |
nn.Sequential
一個有序的容器,神經(jīng)網(wǎng)絡(luò)模塊將按照在傳入構(gòu)造器的順序依次被添加到計算圖中執(zhí)行,同時以神經(jīng)網(wǎng)絡(luò)模塊為元素的有序字典也可以作為傳入?yún)?shù)。
net = nn.Sequential( ('fc1',MyLinear(4, 3)), ('act',nn.ReLU()), ('fc2',MyLinear(3, 1)) ) |
常用的層
全連接層nn.Linear()
torch.nn.Linear(in_features, out_features, bias=True,device=None, dtype=None)
in_features: 輸入維度 out_features:輸出維度 bias: 是否有偏置 |
m = nn.Linear(20, 30) input = torch.randn(128, 20) output = m(input) print(output.size()) |
torch.nn.Dropout
''' p:將元素置0的概率,默認值=0.5 ''' torch.nn.Dropout(p=0.5, inplace=False) |
卷積torch.nn.ConvNd()
class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)
in_channels(int) – 輸入信號的通道 out_channels(int) – 卷積產(chǎn)生的通道 kerner_size(int or tuple) - 卷積核的尺寸 stride(int or tuple, optional) - 卷積步長 padding (int or tuple, optional)- 輸入的每一條邊補充0的層數(shù) dilation(int or tuple, optional) – 卷積核元素之間的間距 groups(int, optional) – 從輸入通道到輸出通道的阻塞連接數(shù) bias(bool, optional) - 如果bias=True,添加偏置 |
input: (N,C_in,H_in,W_in) N為批次,C_in即為in_channels,即一批內(nèi)輸入二維數(shù)據(jù)個數(shù),H_in是二維數(shù)據(jù)行數(shù),W_in是二維數(shù)據(jù)的列數(shù)
output: (N,C_out,H_out,W_out) N為批次,C_out即為out_channels,即一批內(nèi)輸出二維數(shù)據(jù)個數(shù),H_out是二維數(shù)據(jù)行數(shù),W_out是二維數(shù)據(jù)的列數(shù)
conv2 = nn.Conv2d( in_channels=5, out_channels=32, kernel_size=5, stride=1, padding=2 #padding是需要計算的,padding=(stride-1)/2 ) #只能接受tensor/variable conv2(torch.Tensor(16, 5, 3, 10)) conv2(Variable(torch.Tensor(16, 5, 3, 10))) |
池化
最大池化torch.nn.MaxPoolNd()
torch.nn.MaxPool2d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False)
kernel_size- 窗口大小 stride- 步長。默認值是kernel_size padding - 補0數(shù) dilation– 控制窗口中元素步幅的參數(shù) return_indices - 如果等于True,會返回輸出最大值的序號,對于上采樣操作會有幫助 ceil_mode - 如果等于True,計算輸出信號大小的時候,會使用向上取整,代替默認的向下取的操作 |
max2=torch.nn.MaxPool2d(3,1,0,1) max2(torch.Tensor(16,15,15,14)) #output_shape=torch.Size([16, 15, 13, 12]) |
均值池化torch.nn.AvgPoolNd()
kernel_size - 池化窗口大小 stride- 步長。默認值是kernel_size padding- 輸入的每一條邊補充0的層數(shù) dilation – 一個控制窗口中元素步幅的參數(shù) return_indices - 如果等于True,會返回輸出最大值的序號,對于上采樣操作會有幫助 ceil_mode - 如果等于True,計算輸出信號大小的時候,會使用向上取整,代替默認的向下取整的操作 |
torch.nn.AvgPool2d(kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True) |
反池化
是池化的一個“逆”過程,但“逆”只是通過上采樣恢復到原來的尺寸,像素值是不能恢復成原來一模一樣,因為像最大池化是不可逆的,除最大值之外的像素都已經(jīng)丟棄了。
最大值反池化nn.MaxUnpool2d()
功能:對二維圖像進行最大值池化上采樣
參數(shù):
kernel_size- 窗口大小 stride - 步長。默認值是kernel_size padding - 補0數(shù) |
torch.nn.MaxUnpool2d(kernel_size, stride=None, padding=0) |
img_tensor=torch.Tensor(16,5,32,32) # 上采樣 max_pool = nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2), return_indices=True, ceil_mode=True) img_pool, indices = max_pool(img_tensor) # 下采樣 img_unpool = torch.rand_like(img_pool, dtype=torch.float) # 輸入圖像的大小和上采樣的大小保持一致 max_unpool = nn.MaxUnpool2d((2, 2), stride=(2, 2)) img_unpool = max_unpool(img_unpool, indices) |
組合池化
組合池化同時利用最大值池化與均值池化兩種的優(yōu)勢而引申的一種池化策略。常見組合策略有兩種:Cat與Add。其代碼描述如下:
def add_avgmax_pool2d(x, output_size=1): x_avg = F.adaptive_avg_pool2d(x, output_size) x_max = F.adaptive_max_pool2d(x, output_size) return 0.5 * (x_avg + x_max) def cat_avgmax_pool2d(x, output_size=1): x_avg = F.adaptive_avg_pool2d(x, output_size) x_max = F.adaptive_max_pool2d(x, output_size) return torch.cat([x_avg, x_max], 1) |
正則化層
Transformer相關(guān)Normalization方式
BatchNorm
torch.nn.BatchNorm1d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) torch.nn.BatchNorm2d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) torch.nn.BatchNorm3d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) |
參數(shù):
num_features: 來自期望輸入的特征數(shù),該期望輸入的大小為batch_size × num_features [× width],和之前輸入卷積層的channel位的維度數(shù)目相同 eps: 為保證數(shù)值穩(wěn)定性(分母不能趨近或取0),給分母加上的值。默認為1e-5。 momentum: 動態(tài)均值和動態(tài)方差所使用的動量。默認為0.1。 affine: 布爾值,當設(shè)為true,給該層添加可學習的仿射變換參數(shù)。 track_running_stats:布爾值,當設(shè)為true,記錄訓練過程中的均值和方差; |
# With Learnable Parameters m = nn.BatchNorm2d(5) # Without Learnable Parameters m = nn.BatchNorm2d(5, affine=False) inputs = torch.randn(20, 5, 35, 45) output = m(inputs) |
LayerNorm
torch.nn.LayerNorm(normalized_shape, eps=1e-05, elementwise_affine=True) |
參數(shù):
normalized_shape: 輸入尺寸 [× normalized_shape[0] × normalized_shape[1]×…× normalized_shape[?1]] eps: 為保證數(shù)值穩(wěn)定性(分母不能趨近或取0),給分母加上的值。默認為1e-5。 elementwise_affine: 布爾值,當設(shè)為true,給該層添加可學習的仿射變換參數(shù)。 |
LayerNorm
就是對(2, 2,4), 后面這一部分進行整個的標準化??梢岳斫鉃閷φ麄€圖像進行標準化。
x_test = np.array([[[1,2,-1,1],[3,4,-2,2]], [[1,2,-1,1],[3,4,-2,2]]]) x_test = torch.from_numpy(x_test).float() m = nn.LayerNorm(normalized_shape = [2,4]) output = m(x_test) |
InstanceNorm
torch.nn.InstanceNorm1d(num_features, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False) torch.nn.InstanceNorm2d(num_features, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False) torch.nn.InstanceNorm3d(num_features, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False) |
參數(shù):
num_features: 來自期望輸入的特征數(shù),該期望輸入的大小為batch_size x num_features [x width] eps: 為保證數(shù)值穩(wěn)定性(分母不能趨近或取0),給分母加上的值。默認為1e-5。 momentum: 動態(tài)均值和動態(tài)方差所使用的動量。默認為0.1。 affine: 布爾值,當設(shè)為true,給該層添加可學習的仿射變換參數(shù)。 track_running_stats:布爾值,當設(shè)為true,記錄訓練過程中的均值和方差; |
InstanceNorm
就是對(2, 2, 4)最后這一部分進行Norm。
x_test = np.array([[[1,2,-1,1],[3,4,-2,2]], [[1,2,-1,1],[3,4,-2,2]]]) x_test = torch.from_numpy(x_test).float() m = nn.InstanceNorm1d(num_features=2) output = m(x_test) |
GroupNorm
torch.nn.GroupNorm(num_groups, num_channels, eps=1e-05, affine=True) |
參數(shù):
num_groups:需要劃分為的groups num_features: 來自期望輸入的特征數(shù),該期望輸入的大小為batch_size x num_features [x width] eps: 為保證數(shù)值穩(wěn)定性(分母不能趨近或取0),給分母加上的值。默認為1e-5。 momentum: 動態(tài)均值和動態(tài)方差所使用的動量。默認為0.1。 affine: 布爾值,當設(shè)為true,給該層添加可學習的仿射變換參數(shù)。 |
當GroupNorm中g(shù)roup的數(shù)量是1的時候, 是與上面的LayerNorm是等價的。
x_test = np.array([[[1,2,-1,1],[3,4,-2,2]], [[1,2,-1,1],[3,4,-2,2]]]) x_test = torch.from_numpy(x_test).float() # Separate 2 channels into 1 groups (equivalent with LayerNorm) m = nn.GroupNorm(num_groups=1, num_channels=2, affine=False) output = m(x_test) |
當GroupNorm中num_groups的數(shù)量等于num_channel的數(shù)量,與InstanceNorm等價。
# Separate 2 channels into 2 groups (equivalent with InstanceNorm) m = nn.GroupNorm(num_groups=2, num_channels=2, affine=False) output = m(x_test) |
激活函數(shù)
參考資料:GELU 激活函數(shù)
torch.nn.GELU
bert源碼給出的GELU代碼pytorch版本表示如下:
def gelu(input_tensor): cdf = 0.5 * (1.0 + torch.erf(input_tensor / torch.sqrt(2.0))) return input_tesnsor*cdf |
torch.nn.ELU(alpha=1.0,inplace=False)
def elu(x,alpha=1.0,inplace=False): return max(0,x)+min(0,alpha?(exp(x)?1)) |
α是超參數(shù),默認為1.0
torch.nn.LeakyReLU(negative_slope=0.01,inplace=False)
def LeakyReLU(x,negative_slope=0.01,inplace=False): return max(0,x)+negative_slope?min(0,x)
其中 negative_slope是超參數(shù),控制x為負數(shù)時斜率的角度,默認為1e-2
torch.nn.PReLU(num_parameters=1,init=0.25)
def PReLU(x,num_parameters=1,init=0.25): return max(0,x)+init?min(0,x)
其中a 是一個可學習的參數(shù),當不帶參數(shù)調(diào)用時,即nn.PReLU(),在所有的輸入通道上使用同一個a,當帶參數(shù)調(diào)用時,即nn.PReLU(nChannels),在每一個通道上學習一個單獨的a。
注意:當為了獲得好的performance學習一個a時,不要使用weight decay。
num_parameters:要學習的a的個數(shù),默認1
init:a的初始值,默認0.25
torch.nn.ReLU(inplace=False)
CNN中最常用ReLu。
def ReLU(x,inplace=False): return max(0,x)
torch.nn.ReLU6(inplace=False)
def ReLU6(x,inplace=False): return min(max(0,x),6)
torch.nn.SELU(inplace=False)
def SELU(x,inplace=False): alpha=1.6732632423543772848170429916717 scale=1.0507009873554804934193349852946 return scale?(max(0,*x*)+min(0,alpha?(exp(x)?1)))
torch.nn.CELU(alpha=1.0,inplace=False)
def CELU(x,alpha=1.0,inplace=False): return max(0,x)+min(0,alpha?(exp(x/alpha)?1))
其中α 默認為1.0
torch.nn.Sigmoid
def Sigmoid(x): return 1/(np.exp(-x)+1)
torch.nn.LogSigmoid
def LogSigmoid(x): return np.log(1/(np.exp(-x)+1))
torch.nn.Tanh
def Tanh(x): return (np.exp(x)-np.exp(-x))/(np.exp(x)+np.exp(-x))
torch.nn.Tanhshrink
def Tanhshrink(x): return x-(np.exp(x)-np.exp(-x))/(np.exp(x)+np.exp(-x))
torch.nn.Softplus(beta=1,threshold=20)
該函數(shù)可以看作是ReLu的平滑近似。
def Softplus(x,beta=1,threshold=20): return np.log(1+np.exp(beta*x))/beta
torch.nn.Softshrink(lambd=0.5)
λ的值默認設(shè)置為0.5
def Softshrink(x,lambd=0.5): if x>lambd:return x-lambd elif x<-lambd:return x+lambd else:return 0
nn.Softmax
m = nn.Softmax(dim=1) input = torch.randn(2, 3) output = m(input)
參考資料
PyTorch快速入門教程二(線性回歸以及l(fā)ogistic回歸)
以上就是Pytorch模型定義與深度學習自查手冊的詳細內(nèi)容,更多關(guān)于Pytorch深度學習模型定義的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
數(shù)據(jù)挖掘之Apriori算法詳解和Python實現(xiàn)代碼分享
這篇文章主要介紹了數(shù)據(jù)挖掘之Apriori算法詳解和Python實現(xiàn)代碼分享,本文先是對Apriori算法做了詳細介紹,然后給出了Python版實現(xiàn)代碼,需要的朋友可以參考下2014-11-11Python+wxPython實現(xiàn)一個簡單的音樂播放器
這篇文章主要為大家詳細介紹了如何使用Python編程語言和wxPython模塊創(chuàng)建一個簡單的音樂播放器,文中的示例代碼講解詳細,感興趣的可以了解下2023-09-09通過Python腳本+Jenkins實現(xiàn)項目重啟
Jenkins是一個流行的開源自動化服務器,用于快速構(gòu)建、測試和部署軟件,本文主要介紹了通過Python腳本+Jenkins實現(xiàn)項目重啟,具有一定的參考價值,感興趣的可以了解一下2023-10-10Python基于matplotlib實現(xiàn)繪制三維圖形功能示例
這篇文章主要介紹了Python基于matplotlib實現(xiàn)繪制三維圖形功能,涉及Python使用matplotlib模塊進行三維圖形繪制相關(guān)操作技巧,需要的朋友可以參考下2018-01-01