pytorch神经网络层搭建方法


     神经网络层的搭建主要是两种方法,一种是使用类(继承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....)看做一个神经层。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM