天天看點

nn.Module、nn.Sequential和torch.nn.parameter學習筆記nn.Modulenn.Sequentialtorch.nn.Parameter

nn.Module、nn.Sequential和torch.nn.parameter是利用pytorch建構神經網絡最重要的三個函數。搞清他們的具體用法是學習pytorch的必經之路。

目錄

  • nn.Module
  • nn.Sequential
  • torch.nn.Parameter

nn.Module

nn.Module中,自定義層的步驟:

1.自定義一個Module的子類,實作兩個基本的函數:

(1)構造 init 函數 (2)層的邏輯運算函數,即正向傳播的函數

2.在構造 init 函數中實作層的參數定義。 比如Linear層的權重和偏置,Conv2d層的in_channels, out_channels, kernel_size, stride=1,padding=0, dilation=1, groups=1,bias=True, padding_mode='zeros’這一系列參數;

3.在forward函數裡實作前向運算。 一般都是通過torch.nn.functional.***函數來實作,如果該層含有權重,那麼權重必須是nn.Parameter類型。

4.補充:一般情況下,我們定義的參數是可以求導的,但是自定義操作如不可導,需要實作backward函數。

例:

# 定義一個 my_layer.py
    import torch
    
    class MyLayer(torch.nn.Module):
        '''
        因為這個層實作的功能是:y=weights*sqrt(x2+bias),是以有兩個參數:
        權值矩陣weights
        偏置矩陣bias
        輸入 x 的次元是(in_features,)
        輸出 y 的次元是(out_features,) 故而
        bias 的次元是(in_fearures,),注意這裡為什麼是in_features,而不是out_features,注意體會這裡和Linear層的差別所在
        weights 的次元是(in_features, out_features)注意這裡為什麼是(in_features, out_features),而不是(out_features, in_features),注意體會這裡和Linear層的差別所在
        '''
        def __init__(self, in_features, out_features, bias=True):
            super(MyLayer, self).__init__()  # 和自定義模型一樣,第一句話就是調用父類的構造函數
            self.in_features = in_features
            self.out_features = out_features
            self.weight = torch.nn.Parameter(torch.Tensor(in_features, out_features)) # 由于weights是可以訓練的,是以使用Parameter來定義
            if bias:
                self.bias = torch.nn.Parameter(torch.Tensor(in_features))             # 由于bias是可以訓練的,是以使用Parameter來定義
            else:
                self.register_parameter('bias', None)
    
        def forward(self, input):
            input_=torch.pow(input,2)+self.bias
            y=torch.matmul(input_,self.weight)
            return y

    自定義模型并訓練
    import torch
    from my_layer import MyLayer # 自定義層
    
    
    N, D_in, D_out = 10, 5, 3  # 一共10組樣本,輸入特征為5,輸出特征為3 
    
    # 先定義一個模型
    class MyNet(torch.nn.Module):
        def __init__(self):
            super(MyNet, self).__init__()  # 第一句話,調用父類的構造函數
            self.mylayer1 = MyLayer(D_in,D_out)
    
        def forward(self, x):
            x = self.mylayer1(x)
    
            return x
    
    model = MyNet()
    print(model)
    '''運作結果為:
    MyNet(
    (mylayer1): MyLayer()   # 這就是自己定義的一個層
    )
    '''

    下面開始訓練
    # 建立輸入、輸出資料
    x = torch.randn(N, D_in)  #(10,5)
    y = torch.randn(N, D_out) #(10,3)
    
    
    #定義損失函數
    loss_fn = torch.nn.MSELoss(reduction='sum')
    
    learning_rate = 1e-4
    #構造一個optimizer對象
    optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
    
    for t in range(10): # 
        
        # 第一步:資料的前向傳播,計算預測值p_pred
        y_pred = model(x)
    
        # 第二步:計算計算預測值p_pred與真實值的誤差
        loss = loss_fn(y_pred, y)
        print(f"第 {t} 個epoch, 損失是 {loss.item()}")
    
        # 在反向傳播之前,将模型的梯度歸零,這
        optimizer.zero_grad()
    
        # 第三步:反向傳播誤差
        loss.backward()
    
        # 直接通過梯度一步到位,更新完整個網絡的訓練參數
        optimizer.step()
           

nn.Sequential

torch.nn.Sequential是一個Sequential容器,子產品将按照構造函數中傳遞的順序添加到子產品中。

與nn.Module相同,nn.Sequential也是用來建構神經網絡的,但nn.Sequential不需要像nn.Module那麼多過程,可以快速建構神經網絡。

使用nn.Module可以根據自己的需求改變傳播過程。

model = nn.Sequential(
          nn.Conv2d(1,20,5),
          nn.ReLU(),
          nn.Conv2d(20,64,5),
          nn.ReLU()
        )
           

這個建構網絡的方法工作量略有減少,但有特殊需求的網絡還是要用nn.Module。

torch.nn.Parameter

torch.nn.Parameter是繼承自torch.Tensor的子類,其主要作用是作為nn.Module中的可訓練參數使用。它與torch.Tensor的差別就是nn.Parameter會自動被認為是module的可訓練參數,即加入到parameter()這個疊代器中去;而module中非nn.Parameter()的普通tensor是不在parameter中的。

nn.Parameter的對象的requires_grad屬性的預設值是True,即是可被訓練的,這與torh.Tensor對象的預設值相反。

在nn.Module類中,pytorch也是使用nn.Parameter來對每一個module的參數進行初始化的。

例:

class Linear(Module):
    r"""Applies a linear transformation to the incoming data: :math:`y = xA^T + b`
    Args:
        in_features: size of each input sample
        out_features: size of each output sample
        bias: If set to ``False``, the layer will not learn an additive bias.
            Default: ``True``
    Shape:
        - Input: :math:`(N, *, H_{in})` where :math:`*` means any number of
          additional dimensions and :math:`H_{in} = \text{in\_features}`
        - Output: :math:`(N, *, H_{out})` where all but the last dimension
          are the same shape as the input and :math:`H_{out} = \text{out\_features}`.
    Attributes:
        weight: the learnable weights of the module of shape
            :math:`(\text{out\_features}, \text{in\_features})`. The values are
            initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`, where
            :math:`k = \frac{1}{\text{in\_features}}`
        bias:   the learnable bias of the module of shape :math:`(\text{out\_features})`.
                If :attr:`bias` is ``True``, the values are initialized from
                :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
                :math:`k = \frac{1}{\text{in\_features}}`
    Examples::
        >>> m = nn.Linear(20, 30)
        >>> input = torch.randn(128, 20)
        >>> output = m(input)
        >>> print(output.size())
        torch.Size([128, 30])
    """
    __constants__ = ['in_features', 'out_features']

    def __init__(self, in_features, out_features, bias=True):
        super(Linear, self).__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.weight = Parameter(torch.Tensor(out_features, in_features))
        if bias:
            self.bias = Parameter(torch.Tensor(out_features))
        else:
            self.register_parameter('bias', None)
        self.reset_parameters()

    def reset_parameters(self):
        init.kaiming_uniform_(self.weight, a=math.sqrt(5))
        if self.bias is not None:
            fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
            bound = 1 / math.sqrt(fan_in)
            init.uniform_(self.bias, -bound, bound)

    def forward(self, input):
        return F.linear(input, self.weight, self.bias)

    def extra_repr(self):
        return 'in_features={}, out_features={}, bias={}'.format(
            self.in_features, self.out_features, self.bias is not None
        )
           

顯然,在__init__(self, in_features, out_features, bias=True)中,下面的代碼使用了nn.Parameter()對weights進行了初始化

參考:

https://blog.csdn.net/qq_27825451/article/details/90705328

https://blog.csdn.net/qq_28753373/article/details/104179354

繼續閱讀