神經網絡層的搭建主要是兩種方法,一種是使用類(繼承torch.nn.Moudle),一種是使用torch.nn.Sequential來快速搭建。
1)首先我們先加載數據:
import torch
import torch.nn.functional as F
#回歸問題 x=torch.unsqueeze(torch.linspace(-1,1,100),dim=1) y=x.pow(2)+0.2*torch.rand(x.size())
2)兩種方法的模板:
2.1: 類(class):這基本就是固定格式,init中定義每個神經層的神經元個數,和神經元層數,forward是繼承nn.Moudle中函數,來實現前向反饋(加上激勵函數)
#method1 class Net(torch.nn.Module): def __init__(self): super(Net, self).__init__() pass def forward(self,x): pass
比如:
#method1 class Net(torch.nn.Module): def __init__(self): super(Net, self).__init__() self.hidden=torch.nn.Linear(1,10) self.prediction=torch.nn.Linear(10,1) def forward(self,x): x=F.relu(self.hidden(x)) #使用relu作為激勵函數 x=self.prediction(x) #最后一個隱藏層到輸出層沒有使用激勵函數,你也可以加上(一般不加) return x net=Net() print(net) ''' #輸出: Net( (hidden): Linear(in_features=1, out_features=10, bias=True) #hidden就是self.hidden,沒有特殊意義,你自己可以命名別的 (prediction): Linear(in_features=10, out_features=1, bias=True) ) '''
2.2:快速搭建
模板:
net2=torch.nn.Sequential( )
比如:net2 = torch.nn.Sequential(
net2 = torch.nn.Sequential(
torch.nn.Linear(1, 10), torch.nn.ReLU(), torch.nn.Linear(10, 1) )
print(net2)
'''
Sequential ( (0): Linear (1 -> 10) (1): ReLU () (2): Linear (10 -> 1) )
'''
兩者大致相同,稍微有區別的地方就是在於快速搭建中激勵函數(relu....)看做一個神經層。