pytorch之 nn.Modlue及nn.Linear 源碼理解

本文轉自: https://blog.csdn.net/dss_dssssd/article/details/82977170

 

先看一個列子:

import torch
from torch import nn

m = nn.Linear(20, 30)
input = torch.randn(128, 20)
output = m(input)

output.size()


out:

torch.Size([128, 30])

剛開始看這份代碼是有點迷惑的,m是類對象,而直接像函數一樣調用m,m(input)
重點:

nn.Module 是所有神經網絡單元(neural network modules)的基類
pytorch在nn.Module中,實現了__call__方法,而在__call__方法中調用了forward函數。

經過以上兩點。上述代碼就不難理解。
接下來看一下源碼:
https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/module.py

再來看一下nn.Linear
https://pytorch.org/docs/stable/_modules/torch/nn/modules/linear.html
主要看一下forward函數:

返回的是:
input∗weight+biasinput∗weight+bias      input * weight + biasinput∗weight+bias的線性函數
此時再看一下這一份代碼:
import torch
from torch import nn

m = nn.Linear(20, 30)
input = torch.randn(128, 20)
output = m(input)

output.size()
12345678
首先創建類對象m,然後通過m(input)實際上調用__call__(input),然後__call__(input)調用
forward()函數,最後返回計算結果爲:
[128,20]×[20,30]=[128,30][128,20]×[20,30]=[128,30]      [128, 20] \times [20, 30] = [128, 30][128,20]×[20,30]=[128,30]
所以自己創建多層神經網絡模塊時,只需要在實現__init__和forward即可.
接下來看一個簡單的三層神經網絡的例子:
# define three layers
class simpleNet(nn.Module):

    def __init__(self, in_dim, n_hidden_1, n_hidden_2, out_dim):
        super().__init__()
        self.layer1 = nn.Linear(in_dim, n_hidden_1)
        self.layer2 = nn.Linear(n_hidden_1, n_hidden_2)
        self.layer3 = nn.Linear(n_hidden_2, out_dim)

    def forward(self, x):
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)

        return x

12345678910111213141516
以下爲各層神經元個數:
輸入: in_dim
第一層: n_hidden_1
第二層:n_hidden_2
第三層(輸出層):out_dim

 


--------------------- 
作者:墨氳 
來源:CSDN 
原文:https://blog.csdn.net/dss_dssssd/article/details/82977170 
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章