nn.module类搭建简单神经网络

nn.Module是PyTorch提供的神经网络类,并在类中实现了网络各层 的定义及前向计算与反向传播机制。在实际使用时,如果想要实现某个 神经网络,只需继承nn.Module,在初始化中定义模型结构与参数,在 函数forward()中编写网络前向过程即可。
下面具体以一个由两个全连接层组成的感知机为例,介绍如何使用 nn.Module构造模块化的神经网络。新建一个perception.py文件,内容如 下:

import torch
from torch import nn
#先建立一个全连接的子module,继承nn.module
class Linear(nn.Module):
    def _init_(self,in_dim,out_dim):#调用nn.module的构造函数
    super(Linear,self)._init_()
    self.w=nn.Parameter(torch.randn(in_dim,out_dim))
   self.b=nn.parameter(torch.randn(out_dim))
   #使用Parameter来构造需要学习的参数
def forward(self.w):
    #再forward中实现前向传播过程
    x=x.matmul(self.w)#使用matmul矩阵相乘
    y=x+self.b.expand_as(x)#expand_as使矩阵形状一直
    return y
#构建感知机类,调用linear的子module
class Perception(nn.module):
    def _init_(self,in_dim,out_dim):
        super(Perception,self)._init_()
        self.layer1=linear(in_dim,hid_dim)
        self.layer2(hid_dim,out_dim)
    def forward(self,x):
         x=self.layer1(x)
         y=torch.sigmoid(x)
         yself.layer2(y)
         y=torch.sigmoid(y)
         return y
        

编写完网络模块后,可以在终端调用

import torch
from perception import Perception
perception = Perception(2,3,2)

1.nn.Parameter函数
在类的__init__()中需要定义网络学习的参数,在此使用 nn.Parameter()函数定义了全连接中的ω和b,这是一种特殊的Tensor的构 造方法,默认需要求导,即requires_grad为True。
2.forward()函数与反向传播
forward()函数用来进行网络的前向传播,并需要传入相应的 Tensor,例如上例的perception(data)即是直接调用了forward()。
3.nn.Sequential()模块
当模型中只是简单的前馈网络时,即上一层的输出直接作为下一层 的输入,这时可以采用nn.Sequential()模块来快速搭建模型,而不必手动 在forward()函数中一层一层地前向传播。因此,如果想快速搭建模型而 不考虑中间过程的话,推荐使用nn.Sequential()模块。
在上面的例子中,Perception类中的layer1与layer2是直接传递的, 因此该Perception类可以使用nn.Sequential()快速搭建。在此新建一个 perception_sequential.py文件,内容如下:

from torch import nn 
class Perception(nn.Module):
   def __init__(self, in_dim, hid_dim, out_dim):
       super(Perception, self).__init__()
       # 利用nn.Sequential()快速搭建网络模块
       self.layer = nn.Sequential(
             nn.Linear(in_dim, hid_dim),
             nn.Sigmoid(),
             nn.Linear(hid_dim, out_dim),
             nn.Sigmoid() )
   def forward(self, x):
        y = self.layer(x)
        return y

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值