nn.Module、nn.Sequential和torch.nn.parameter是利用pytorch构建神经网络最重要的三个函数。搞清他们的具体用法是学习pytorch的必经之路。

目录

  • nn.Module
  • nn.Sequential
  • torch.nn.Parameter

nn.Module

nn.Module中,自定义层的步骤:
1.自定义一个Module的子类,实现两个基本的函数:
(1)构造 init 函数 (2)层的逻辑运算函数,即正向传播的函数

2.在构造 init 函数中实现层的参数定义。 比如Linear层的权重和偏置,Conv2d层的in_channels, out_channels, kernel_size, stride=1,padding=0, dilation=1, groups=1,bias=True, padding_mode='zeros’这一系列参数;
3.在forward函数里实现前向运算。 一般都是通过torch.nn.functional.***函数来实现,如果该层含有权重,那么权重必须是nn.Parameter类型。
4.补充:一般情况下,我们定义的参数是可以求导的,但是自定义操作如不可导,需要实现backward函数。

例:

# 定义一个 my_layer.pyimport torchclass MyLayer(torch.nn.Module):'''因为这个层实现的功能是:y=weights*sqrt(x2+bias),所以有两个参数:权值矩阵weights偏置矩阵bias输入 x 的维度是(in_features,)输出 y 的维度是(out_features,) 故而bias 的维度是(in_fearures,),注意这里为什么是in_features,而不是out_features,注意体会这里和Linear层的区别所在weights 的维度是(in_features, out_features)注意这里为什么是(in_features, out_features),而不是(out_features, in_features),注意体会这里和Linear层的区别所在'''def __init__(self, in_features, out_features, bias=True):super(MyLayer, self).__init__()  # 和自定义模型一样,第一句话就是调用父类的构造函数self.in_features = in_featuresself.out_features = out_featuresself.weight = torch.nn.Parameter(torch.Tensor(in_features, out_features)) # 由于weights是可以训练的,所以使用Parameter来定义if bias:self.bias = torch.nn.Parameter(torch.Tensor(in_features))             # 由于bias是可以训练的,所以使用Parameter来定义else:self.register_parameter('bias', None)def forward(self, input):input_=torch.pow(input,2)+self.biasy=torch.matmul(input_,self.weight)return y自定义模型并训练import torchfrom my_layer import MyLayer # 自定义层N, D_in, D_out = 10, 5, 3  # 一共10组样本,输入特征为5,输出特征为3 # 先定义一个模型class MyNet(torch.nn.Module):def __init__(self):super(MyNet, self).__init__()  # 第一句话,调用父类的构造函数self.mylayer1 = MyLayer(D_in,D_out)def forward(self, x):x = self.mylayer1(x)return xmodel = MyNet()print(model)'''运行结果为:MyNet((mylayer1): MyLayer()   # 这就是自己定义的一个层)'''下面开始训练# 创建输入、输出数据x = torch.randn(N, D_in)  #(10,5)y = torch.randn(N, D_out) #(10,3)#定义损失函数loss_fn = torch.nn.MSELoss(reduction='sum')learning_rate = 1e-4#构造一个optimizer对象optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)for t in range(10): # # 第一步:数据的前向传播,计算预测值p_predy_pred = model(x)# 第二步:计算计算预测值p_pred与真实值的误差loss = loss_fn(y_pred, y)print(f"第 {t} 个epoch, 损失是 {loss.item()}")# 在反向传播之前,将模型的梯度归零,这optimizer.zero_grad()# 第三步:反向传播误差loss.backward()# 直接通过梯度一步到位,更新完整个网络的训练参数optimizer.step()

nn.Sequential

torch.nn.Sequential是一个Sequential容器,模块将按照构造函数中传递的顺序添加到模块中。
与nn.Module相同,nn.Sequential也是用来构建神经网络的,但nn.Sequential不需要像nn.Module那么多过程,可以快速构建神经网络。
使用nn.Module可以根据自己的需求改变传播过程。

        model = nn.Sequential(nn.Conv2d(1,20,5),nn.ReLU(),nn.Conv2d(20,64,5),nn.ReLU())

这个构建网络的方法工作量略有减少,但有特殊需求的网络还是要用nn.Module。

torch.nn.Parameter

torch.nn.Parameter是继承自torch.Tensor的子类,其主要作用是作为nn.Module中的可训练参数使用。它与torch.Tensor的区别就是nn.Parameter会自动被认为是module的可训练参数,即加入到parameter()这个迭代器中去;而module中非nn.Parameter()的普通tensor是不在parameter中的。
nn.Parameter的对象的requires_grad属性的默认值是True,即是可被训练的,这与torh.Tensor对象的默认值相反。
在nn.Module类中,pytorch也是使用nn.Parameter来对每一个module的参数进行初始化的。
例:

class Linear(Module):r"""Applies a linear transformation to the incoming data: :math:`y = xA^T + b`Args:in_features: size of each input sampleout_features: size of each output samplebias: If set to ``False``, the layer will not learn an additive bias.Default: ``True``Shape:- Input: :math:`(N, *, H_{in})` where :math:`*` means any number ofadditional dimensions and :math:`H_{in} = \text{in\_features}`- Output: :math:`(N, *, H_{out})` where all but the last dimensionare the same shape as the input and :math:`H_{out} = \text{out\_features}`.Attributes:weight: the learnable weights of the module of shape:math:`(\text{out\_features}, \text{in\_features})`. The values areinitialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`, where:math:`k = \frac{1}{\text{in\_features}}`bias:   the learnable bias of the module of shape :math:`(\text{out\_features})`.If :attr:`bias` is ``True``, the values are initialized from:math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where:math:`k = \frac{1}{\text{in\_features}}`Examples::>>> m = nn.Linear(20, 30)>>> input = torch.randn(128, 20)>>> output = m(input)>>> print(output.size())torch.Size([128, 30])"""__constants__ = ['in_features', 'out_features']def __init__(self, in_features, out_features, bias=True):super(Linear, self).__init__()self.in_features = in_featuresself.out_features = out_featuresself.weight = Parameter(torch.Tensor(out_features, in_features))if bias:self.bias = Parameter(torch.Tensor(out_features))else:self.register_parameter('bias', None)self.reset_parameters()def reset_parameters(self):init.kaiming_uniform_(self.weight, a=math.sqrt(5))if self.bias is not None:fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)bound = 1 / math.sqrt(fan_in)init.uniform_(self.bias, -bound, bound)def forward(self, input):return F.linear(input, self.weight, self.bias)def extra_repr(self):return 'in_features={}, out_features={}, bias={}'.format(self.in_features, self.out_features, self.bias is not None)

显然,在__init__(self, in_features, out_features, bias=True)中,下面的代码使用了nn.Parameter()对weights进行了初始化

参考:
https://blog.csdn.net/qq_27825451/article/details/90705328
https://blog.csdn.net/qq_28753373/article/details/104179354

nn.Module、nn.Sequential和torch.nn.parameter学习笔记相关推荐

  1. PyTorch 笔记(16)— torch.nn.Sequential、torch.nn.Linear、torch.nn.RelU

    PyTorch 中的 torch.nn 包提供了很多与实现神经网络中的具体功能相关的类,这些类涵盖了深度神经网络模型在搭建和参数优化过程中的常用内容,比如神经网络中的卷积层.池化层.全连接层这类层次构 ...

  2. torch分布式训练学习笔记

    分布式通讯包 - torch.distributed 基本 初始化 TCP初始化 共享文件系统初始化 环境变量初始化 组 点对点通信 集体功能 torch.distributed提供了一种类似MPI的 ...

  3. Pytorch中nn.Module和nn.Sequencial的简单学习

    文章目录 前言 1.Python 类 2.nn.Module 和 nn.Sequential 2.1 nn.Module 2.1.1 torch.nn.Module类 2.1.2 nn.Sequent ...

  4. [Pytorch系列-30]:神经网络基础 - torch.nn库五大基本功能:nn.Parameter、nn.Linear、nn.functioinal、nn.Module、nn.Sequentia

    作者主页(文火冰糖的硅基工坊):文火冰糖(王文兵)的博客_文火冰糖的硅基工坊_CSDN博客 本文网址:https://blog.csdn.net/HiWangWenBing/article/detai ...

  5. 43_pytorch nn.Module,模型的创建,构建子模块,API介绍,Sequential(序号),ModuleList,ParameterList,案例等(学习笔记)

    1.40.PyTorch nn.Module 1.40.1.模型的创建 1.40.2.构建子模块 1.40.3.nn.Module API介绍 1.40.3.1.核心功能 1.40.3.2.查看模块 ...

  6. Pytorch —— nn.Module类(nn.sequential)

    对于前面的线性回归模型. Logistic回归模型和神经网络,我们在构建的时候定义了需要的参数.这对于比较小的模型是可行的,但是对于大的模型,比如100 层的神经网络,这个时候再去手动定义参数就显得非 ...

  7. pytorch使用torch.nn.Sequential构建网络

    以一个线性回归的例子为例: 全部代码 import torch import numpy as npdef get_x_y():x = np.random.randint(0, 50, 300)y_v ...

  8. nn.moduleList 和Sequential由来、用法和实例 —— 写网络模型

    对于cnn前馈神经网络如果前馈一次写一个forward函数会有些麻烦,在此就有两种简化方式,ModuleList和Sequential.其中Sequential是一个特殊的module,它包含几个子M ...

  9. PyTorch : torch.nn.xxx 和 torch.nn.functional.xxx

    PyTorch : torch.nn.xxx 和 torch.nn.functional.xxx 在写 PyTorch 代码时,我们会发现在 torch.nn.xxx 和 torch.nn.funct ...

最新文章

  1. MySQL的存储引擎与日志说明
  2. PHP开发APP接口(二)
  3. Viewpager中改变PagerTabStrip的颜色(背景色,指示条颜色,文字颜色)
  4. HighNewTech:横向、纵向动图查看《Why资本寒冬》——根据中国四大行每年(2004年~2018年)贷款主要流向来看当下的资本寒冬
  5. Tasker文件夹说明
  6. OS- -I/O之I/O设备
  7. System V IPC之共享内存
  8. [vue] vue如果想扩展某个现有的组件时,怎么做呢?
  9. MySQL无法启动服务器(1067)
  10. pgsql修改字段长度
  11. UNIAPP使用MathJax解析数学公式
  12. MySQL Front订单信息表,mysqlfront
  13. html 导航栏颜色代码,CSS实现五颜六色按钮组成的导航条效果代码
  14. word文档如何画线条流程图_word怎么画图,如何用word制作流程图
  15. 驾考笔记:科目二考试满分攻略——超详细的点位细节梳理,各种意外情况处理方案整理
  16. 布道微服务_03服务的发布和引用
  17. mysql+纵表和横表_mysql 横表和纵表转换
  18. Remote Sensing投稿经历
  19. lvgl使用旋转编码器做为外部输入设备
  20. html 订阅发布,发布订阅模式.html · Avan/blog_demo_defineProperty - Gitee.com

热门文章

  1. Android Architecture Components
  2. 科普:QUIC协议原理分析
  3. 水文实时在线监测系统
  4. android 群组消息,极光IM- 群组管理 - 极光文档
  5. android手机慢,揭秘Android手机变慢的三大原因与对策
  6. 振兴当当,李国庆如何逐鹿中原?
  7. 模电课设 方波—三角波—正弦波信号发生器
  8. postfix smtpd_recipient_restrictions配置错误导致smtpd问题
  9. 静态时序分析(STA)附秋招面试提问
  10. linux命令--mkdir 与文件权限