先看一個列子:
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+bias input * weight + bias
input∗weight+bias
的線性函數
此時再看一下這一份代碼:
import torch
from torch import nn
m = nn.Linear(20, 30)
input = torch.randn(128, 20)
output = m(input)
output.size()
# 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
以下爲各層神經元個數:
輸入: in_dim
第一層: n_hidden_1
第二層:n_hidden_2
第三層(輸出層):out_dim
轉自:https://blog.csdn.net/dss_dssssd/article/details/82977170