下面是如何自己構建一個層,分為包含自動反向求導和手動反向求導兩種方式,后面會分別構建網絡,對比一下結果對不對。
----------------------------------------------------------
關於Pytorch中的結構層級關系。
最為底層的是torch.relu()、torch.tanh()、torch.ge()這些函數,這些函數個人猜測就是直接用Cuda寫成的,並且封裝成了python接口給python上層調用。
部分函數被torch.nn.functional里面的部分函數模塊調用。這些函數可能會被更為上層的nn.Module調用。
下面以BatchNormalization為例進行分析。
最為底層的是torch.batch_norm()這個函數,是看不到源代碼的,應該是對於cuda代碼的封裝。這個函數會傳入(input, weight, bias, running_mean, running_var, training, momentum, eps)。 再往上時torch.nn.functional里面的函數bacth_norm()。再往上就是torch.nn里面的網絡層,比如,BatchNorm2d()等等。
分析一下BatchNorm2d()里面的主要程序。
import torch import torch.nn as nn from torch.nn import init from torch.nn.parameter import Parameter class BatchNorm(nn.module): def __init__(self,num_features): super(BatchMMNorm,self).__init__() self.weight = Parameter(torch.Tensor(num_features)) self.bias = Parameter(torch.Tensor(num_features)) def reset_parameter(self): init.uniform_(self.weight) init.zeros_(self.bias)
def forward(self,input):
其中Parameter是用以定義可學習的權重參數的,后面還需要初始化參數。