PyTorch 1.0 系列学习教程(3):nn module

Pytorch获取神经网络各层的参数名称及参数值 model.children()函数、model.state_dict()函数、model.parameters()函数和models.named_parameters()函数的实例演示。 阅读详情

NN MODULE

PyTorch:nn

计算图和autograd对于定义复杂操作和自动推导来说是一个非常强大的范式;然而对于大型神经网络来说,原始autograd有点太低级了.
构建神经网络时,我们经常需要思考如何将计算量安排到层中,某些计算有需要学习的参数(learnable parameters)并且在学习过程中需要优化.
在TensorFlow的一些包,像Keras,TensorFlow-Slim,TFLearn都提供原始的计算图的高级抽象,这对构建神经网络是有用的.
PyTorch中,nn包是为了达到同样的目的. nn包定义了一系列
模块(Modules)
,可以粗略的等价于神经网络层. 模块接收输入张量并且计算输出张量,但有时也包含中间状态,例如包含可学习参数的张量. nn包也定义了一系列在训练神经网络时通常会用到的有用的损失函数.
在这个示例中,我们使用nn包来实现我们的两层神经网络.

# -*- coding: utf-8 -*-
import torch

# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10

# Create random Tensors to hold inputs and outputs
x = torch.randn(N, D_in)
y = torch.randn(N, D_out)

# Use the nn package to define our model as a sequence of layers. nn.Sequential
# is a Module which contains other Modules, and applies them in sequence to
# produce its output. Each Linear Module computes output from input using a
# linear function, and holds internal Tensors for its weight and bias.
model = torch.nn.Sequential(
    torch.nn.Linear(D_in, H),
    torch.nn.ReLU(),
    torch.nn.Linear(H, D_out),
)

# The nn package also contains definitions of popular loss functions; in this
# case we will use Mean Squared Error (MSE) as our loss function.
loss_fn = torch.nn.MSELoss(reduction='sum')

learning_rate = 1e-4
for t in range(500):
    # Forward pass: compute predicted y by passing x to the model. Module objects
    # override the __call__ operator so you can call them like functions. When
    # doing so you pass a Tensor of input data to the Module and it produces
    # a Tensor of output data.
    y_pred = model(x)

    # Compute and print loss. We pass Tensors containing the predicted and true
    # values of y, and the loss function returns a Tensor containing the
    # loss.
    loss = loss_fn(y_pred, y)
    print(t, loss.item())

    # Zero the gradients before running the backward pass.
    model.zero_grad()

    # Backward pass: compute gradient of the loss with respect to all the learnable
    # parameters of the model. Internally, the parameters of each Module are stored
    # in Tensors with requires_grad=True, so this call will compute gradients for
    # all learnable parameters in the model.
    loss.backward()

    # Update the weights using gradient descent. Each parameter is a Tensor, so
    # we can access its gradients like we did before.
    with torch.no_grad():
        for param in model.parameters():
            param -= learning_rate * param.grad

PyTorch:optim

到目前为止我们已经更新了我们的模型的权重通过手工的改变包含可学习参数的张量(用torch.no_grad或.data来避免在autograd时跟踪历史). 这对于像随机梯度下降法这种简单的优化算法来说并不是一个很大的负担,但在实践中,我们经常使用更复杂的优化器来训练神经网络,如 AdaGrad, RMSProp, Adam等.
在这个示例中,我们将像之前那样使用nn包定义我们的模型,但我们将是使用有optim包提供的Adam算法来优化模型.

# -*- coding: utf-8 -*-
import torch

# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10

# Create random Tensors to hold inputs and outputs
x = torch.randn(N, D_in)
y = torch.randn(N, D_out)

# Use the nn package to define our model and loss function.
model = torch.nn.Sequential(
    torch.nn.Linear(D_in, H),
    torch.nn.ReLU(),
    torch.nn.Linear(H, D_out),
)
loss_fn = torch.nn.MSELoss(reduction='sum')

# Use the optim package to define an Optimizer that will update the weights of
# the model for us. Here we will use Adam; the optim package contains many other
# optimization algoriths. The first argument to the Adam constructor tells the
# optimizer which Tensors it should update.
learning_rate = 1e-4
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
for t in range(500):
    # Forward pass: compute predicted y by passing x to the model.
    y_pred = model(x)

    # Compute and print loss.
    loss = loss_fn(y_pred, y)
    print(t, loss.item())

    # Before the backward pass, use the optimizer object to zero all of the
    # gradients for the variables it will update (which are the learnable
    # weights of the model). This is because by default, gradients are
    # accumulated in buffers( i.e, not overwritten) whenever .backward()
    # is called. Checkout docs of torch.autograd.backward for more details.
    optimizer.zero_grad()

    # Backward pass: compute gradient of the loss with respect to model
    # parameters
    loss.backward()

    # Calling the step function on an Optimizer makes an update to its
    # parameters
    optimizer.step()

PyTorch:Custom nn Modules

有时候我们想指定比现有的模块更复杂的模型;这时候,你可以通过子类化nn.Module定义你自己的模块,同时定义forward,以接收输入张量以及使用其他模块产生的输出张量,或在张量上进行其他自动微分操作.
在这个示例中我们用自定义的形式实现我们的两层神经网络.

# -*- coding: utf-8 -*-
import torch


class TwoLayerNet(torch.nn.Module):
    def __init__(self, D_in, H, D_out):
        """
        In the constructor we instantiate two nn.Linear modules and assign them as
        member variables.
        """
        super(TwoLayerNet, self).__init__()
        self.linear1 = torch.nn.Linear(D_in, H)
        self.linear2 = torch.nn.Linear(H, D_out)

    def forward(self, x):
        """
        In the forward function we accept a Tensor of input data and we must return
        a Tensor of output data. We can use Modules defined in the constructor as
        well as arbitrary operators on Tensors.
        """
        h_relu = self.linear1(x).clamp(min=0)
        y_pred = self.linear2(h_relu)
        return y_pred


# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10

# Create random Tensors to hold inputs and outputs
x = torch.randn(N, D_in)
y = torch.randn(N, D_out)

# Construct our model by instantiating the class defined above
model = TwoLayerNet(D_in, H, D_out)

# Construct our loss function and an Optimizer. The call to model.parameters()
# in the SGD constructor will contain the learnable parameters of the two
# nn.Linear modules which are members of the model.
criterion = torch.nn.MSELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr=1e-4)
for t in range(500):
    # Forward pass: Compute predicted y by passing x to the model
    y_pred = model(x)

    # Compute and print loss
    loss = criterion(y_pred, y)
    print(t, loss.item())

    # Zero gradients, perform a backward pass, and update the weights.
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

PyTorch:Control Flow + Weight Sharing

作为动态图和权值共享的一个示例,我们将实现一个非常奇怪的模型:一个全连接ReLU网络,其在每个前向传导时在[1,4]选择一个随机数值,将其使用到多个隐含层中,复用相同的权重多次以计算最里层的隐含层.
对于这个模型,我们可以使用常规Python 控制流去实现循环,并且。我们可以在前向传导时通过简单的多次复用相同的模块在最内层实现权重共享.
我们可以容易的将其作为一个模块子类来实现这个模型.

# -*- coding: utf-8 -*-
import random
import torch


class DynamicNet(torch.nn.Module):
    def __init__(self, D_in, H, D_out):
        """
        In the constructor we construct three nn.Linear instances that we will use
        in the forward pass.
        """
        super(DynamicNet, self).__init__()
        self.input_linear = torch.nn.Linear(D_in, H)
        self.middle_linear = torch.nn.Linear(H, H)
        self.output_linear = torch.nn.Linear(H, D_out)

    def forward(self, x):
        """
        For the forward pass of the model, we randomly choose either 0, 1, 2, or 3
        and reuse the middle_linear Module that many times to compute hidden layer
        representations.

        Since each forward pass builds a dynamic computation graph, we can use normal
        Python control-flow operators like loops or conditional statements when
        defining the forward pass of the model.

        Here we also see that it is perfectly safe to reuse the same Module many
        times when defining a computational graph. This is a big improvement from Lua
        Torch, where each Module could be used only once.
        """
        h_relu = self.input_linear(x).clamp(min=0)
        for _ in range(random.randint(0, 3)):
            h_relu = self.middle_linear(h_relu).clamp(min=0)
        y_pred = self.output_linear(h_relu)
        return y_pred


# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10

# Create random Tensors to hold inputs and outputs
x = torch.randn(N, D_in)
y = torch.randn(N, D_out)

# Construct our model by instantiating the class defined above
model = DynamicNet(D_in, H, D_out)

# Construct our loss function and an Optimizer. Training this strange model with
# vanilla stochastic gradient descent is tough, so we use momentum
criterion = torch.nn.MSELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr=1e-4, momentum=0.9)
for t in range(500):
    # Forward pass: Compute predicted y by passing x to the model
    y_pred = model(x)

    # Compute and print loss
    loss = criterion(y_pred, y)
    print(t, loss.item())

    # Zero gradients, perform a backward pass, and update the weights.
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    

参考

[1] pytorch官方网站

Pytorch nn.Module模块详解 torcn.nn是专门为神经网络设计的模块化接口. nn构建于autograd之上,可以用来定义和运行神经网络。 nn.Module是nn中十分重要的类,包含网络各层的定义及forward方法。 如何定义自己的网络: 需要继承nn.Module类,并实现forward方法。 一般把网络中具有可学习参数的层放在构造函数__init__()中。 不具有可学习参数的层(如ReLU)可放在构造函数中,也... 阅读详情

相关推荐

PyTorch 源码解读之 nn.Module:核心网络模块接口详解

PyTorch 源码解读系列更新啦~

qq_39967751的博客 6119

pytorch 打印模型层的名字的多个方式,以及对应显示,删除最后多个层的两种方式

def forward(self, x, last_cont=None): x = self.model(x) if self.use_dcl: mask = self.Convmask(x) mask = self.avgpool2(mask) mask = torch.tanh(ma...

m0_37192554的博客 1万+

pytorch详解nn.Module类,children和modules方法区别

详解nn.Module类,children和modules方法区别 pytorch里面一切自定义操作基本上都是继承nn.Module类来实现的,所以此篇文章来了解下这个核心nn.Module类。 继承nn.Module后具体实现自定义模型类时有两种方式: (1)高层API方法:使用torch.nn.****来实现;,这些接口都是类,类可以存储参数,比如全连接层的权值矩阵、偏置矩阵等都可以作为类的属...

qq_40728805的博客 3046

pytorch nn.Module调用过程详解及weight和bias的值的初始化

首先说明一点: nn.Module 是所有神经网络单元(neural network modules)的基类 pytorch在nn.Module中,实现了__call__方法,而在__call__方法中调用了forward函数。 举例说明: x = torch.randn(2, 3) #input 2*3 m = torch.nn.Linear(3, 2)#output 2*2 output = m(x) print(output) 输出结果: tensor([[ 0.1918, -0.1055],

weixin_42713739的博客 1万+

Pytorch继承nn.module和nn.autograd.Function的区别

和 都是 PyTorch 中定义和管理计算图的核心组件,但它们有不同的用途和设计目标。以下是它们之间的主要区别: 是 PyTorch 中最常用的类,用于构建神经网络层和模型。它提供了对神经网络模型的结构化定义,包括前向传播()和参数管理(如权重和偏置的保存与更新)。网络结构定义: 是定义整个神经网络的基础类。你可以通过继承这个类来构建自己的网络。它可以包含多个层(例如卷积层、全连接层、激活函数等),并组织这些层的组合。自动管理参数: 会自动跟踪其子模块的参数(例如卷积核、全连接层的权重和偏置),并且在优化

shengfzy的博客 1264

pytorch nn.module模块及常见算子

torch.nn是专门为神经网络设计的模块化接口,nn构建于autograd之上,可以用来定义和运行神经网络。 nn.module是nn中十分重要的类,包含网络各层的定义及forward方法。 若需要定义自己的网络: (1)需要继承nn.module类,并实现forward方法 (2)一般把网络中具有可学习参数的层放在构造函数_init_()中,不具有可学习参数的层(如...

shuijinghua的博客 2129

Pytorch—模型构造(Module)

Pytorch—模型构造(Module) 1. 模型构造(Module类) 1.1. Module简介 在这个系列之前的文章中,在自定义模型的时候,始终都都需要继承nn.Module类。这里我们对于这个类进行一下解释。 众所周知,Pytorch是基于动态图的模型搭建方式,我们可以随机的在网络中添加或者删除网络层。在搭建我们自己的网络结构的时候,我们需要基础nn.Module类作为父类。然后在我们自定义类的内部添加不同的网络层。其中nn.Module类是nn模块中提供的一个模型构造类,是所有神经网络模块的基础

hei653779919的博客 1531

cadence capture CIS 之使用access创建数据库(.mdb)

cadence capture CIS 之使用access创建数据库(.mdb)准备工作新建数据库 准备工作 1、一台电脑; 2、安装 Microsoft access database; 新建数据库 打开你准备创建数据库的位置,右键单击——》新建——》 Microsoft access database(注意:文件格式要选*.mdb) 打开数据库文件,创建——》表; 对数据表进行编辑,编辑表头、编辑表的内容、增加表的数量; 编辑表头:选中要编辑的表——》表设计 编辑内容:类似于excel添

weixin_42256550的博客 3146

PyTorch-nn.Module

PyTorch关于神经网络的一些层的应用。

qq_61706112的博客 1996

BMS | 从一串到几百串硬件架构简介

锂电池在生活中越来越多的方面扮演能源的角色,除了大家熟知的电动汽车行业,在一些消费类,工业类电子产品比如手机,电动自行车,电动工具中都有应用,追本溯源今天我们一起来学习下最基础的BMS架构。 1~4串架构 以S8241为代表的无通信/无固件/模拟器件 可实现过充保护、过放保护、过流/短路,参数由器件后缀代码决定;通信类手持设备供电系统;1~4节电池保护板架构 如图使用S-8241系列保护IC,一对充放电MOS管控制充放电的回路的切断和接通,系统供电来自于电芯电压,VM引脚用于检测过...

ningvay的博客 9916

FLUENT UDF编译及蒸发冷凝相关问题

蒸发冷凝与相间传质

weixin_48029137的博客 1万+

pytorch教程之nn.Module类详解——使用Module类来自定义模型

前言:pytorch中对于一般的序列模型,直接使用torch.nn.Sequential类及可以实现,这点类似于keras,但是更多的时候面对复杂的模型,比如:多输入多输出、多分支模型、跨层连接模型、带有自定义层的模型等,就需要自己来定义一个模型了。本文将详细说明如何让使用Mudule类来自定义一个模型。 一、torch.nn.Module类概述 个人理解,pytorch不...

MIss-Y的博客 16万+

Bootloader Design of PIC18 series MCU

注意:下列描述是在PIC单片机上启用Bootloader的一个相关知识的近似完备集。所有需要了解的,与bootloader与用户态程序交互的理论知识都已给出。包含内存组织,跳转,中断等必备功能的描述。

含光左卫的工作笔记集 1266

pytorch教程之nn.Module类详解——使用Module类来自定义网络层

前言:前面介绍了如何自定义一个模型——通过继承nn.Module类来实现,在__init__构造函数中申明各个层的定义,在forward中实现层之间的连接关系,实际上就是前向传播的过程。 事实上,在pytorch里面自定义层也是通过继承自nn.Module类来实现的,我前面说过,pytorch里面一般是没有层的概念,层也是当成一个模型来处理的,这里和keras是不一样的。前面...

MIss-Y的博客 10万+

Grok-1.5+Ollama企业级本地化部署与合规实践指南

本文详细介绍了Grok-1.5+Ollama企业级本地化部署与合规实践指南,重点分析了本地化部署的成本优势和数据主权保障。通过RTX 4090显卡的硬件选型、Ubuntu 22.04系统优化及部署流程中的关键陷阱规避,为企业提供了高效、安全的AI模型部署方案。特别适合金融、医疗等敏感行业。

weixin_29094539的博客 180

YOLOv13涨点改进| CVPR 2026 |独家创新首发、主干改进篇 |利用RIS-PiDiNet主干让YOLOv13更加强大!适合遥感目标检测、小目标检测、旋转目标检测,变化检测,图像分割涨点

🔥本文提出了一种改进的RIS-PiDiNet主干网络,通过引入几何先验构建几何一致性检测器,显著提升了模型在任意方向、结构规则目标场景下的检测性能。包含两个核心模块:S-PDC利用极谐变换的谐波核建模目标结构对称性,RIS-PDC通过SO(2)群平均实现旋转不变性。网络采用基于RIS-block的主干结构并融合轻量级LBP特征,增强了细粒度结构表达能力。实验表明,该方法特别适用于遥感和复杂几何分布场景,能有效提升目标检测的鲁棒性和精度。文章还详细介绍了如何将RIS-PiDiNet集成到YOLOv13框架

Ai缝合怪、助力小伙伴高效发论文 89

Pytorch nn.Module详解

torch.nn.Module 是 PyTorch 中所有神经网络模块的基类,提供了构建神经网络模型的基本框架。通过继承 nn.Module,可以方便地创建自定义的神经网络模块,实现复杂的神经网络结构。下面详细介绍 nn.Module 的核心概念、使用方法和注意事项。

fydw_715的博客 3036

Qt和FFmpeg的视频压缩工具

m_progressDialog = new QProgressDialog("正在压缩视频...", "取消", 0, 100, parent);QString file = QFileDialog::getOpenFileName(this, "选择视频文件", "",QString file = QFileDialog::getSaveFileName(this, "保存压缩文件", "",QMessageBox::warning(parent, "错误", "请设置输入和输出文件路径");

寒寒豆豆软件公司的博客 101

PyTorch之nn.Module、nn.Sequential、nn.ModuleList使用详解

nn.functional 中的函数没有可学习的参数,与nn.Module 中的层不同。其实这两种方法都是使用relu激活,只是使用的场景不一样,F.relu()是函数调用,一般使用在foreward函数里。在上述示例中,我们首先导入nn.functional 模块,然后在网络的forward 方法中使用F.relu 函数作为激活函数。的主要优势是它的计算效率和灵活性,因为它允许你以函数的方式直接调用这些操作,而不需要创建额外的层。是PyTorch中一个重要的模块,它包含了许多用于构建神经网络的函数。

酒酿小圆子呀~ 6107

Unity 之jenkins自动打包

1.Jenkins 是什么? jenkins官方网址:https://www.jenkins.io/zh/ Jenkins是一款开源 CI&CD(持续集成&持续部署) 软件,用于自动化各种任务,包括构建、测试和部署软件。 简易安装:Jenkins 是一个基于 Java 的独立程序,可以立即运行,包含 Windows、Mac OS X 和其他类 Unix 操作系统。Jenkins 支持各种运行方式,可通过系统包、Docker 或者通过一个独立的 Java 程序。 插件扩展:通过更新中心中的

TxNet 2132

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

Pytorch笔记 之 torch.nn 模块简介

参考翻译 [What is torch.nn really?](https://pytorch.org/tutorials/beginner/nn_tutorial.html) 主要是对 PyTorch 框架的各模块进行简要介绍 一定程度上是 PyTorch 的入门笔记 假设已经对神经网络相关基础知识有了一定了解 (或实现过机器学习梯度下降相关代码)

子耶 6万+

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

pytorch里面nn.Module讲解

nn.Module是在pytorch使用非常广泛的类,搭建网络基本都需要用到这个。 当我们搭建自己的网络时,可以继承官方写好的nn.Module模块,为什么要用这个呢?好处如下: 1.可以提供一些现成的基本模块比如: Linear、ReLU、Sigmoid、Conv2d、Dropout 不用自己一个一个的写这些函数了,这也是为什么我们用框架的原因之一吧。 2. 容器 比如我们经常用到的 nn...

yolov4的博客 6406

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

PyTorch基础:神经网络工具箱torch.nn(nn.Module类)

perception.py import torch from torch import nn #首先建立一个全连接的子module,继承nn.Module class Linear(nn.Module): def __init__(self, in_dim, out_dim): super(Linear, self).__init__() #调用nn.Module的构造函数 #使用nn.Parameter来构造需要学习的参数 self.w

weixin_42782833的博客 7319

PyTorch之nn.Module与nn.functional用法区别

其实这两种方法都是使用relu激活,只是使用的场景不一样,F.relu()是函数调用,一般使用在foreward函数里。而nn.ReLU()是模块调用,一般在定义网络层的时候使用。在上述示例中,我们首先导入nn.functional 模块,然后在网络的forward 方法中使用F.relu 函数作为激活函数。的主要优势是它的计算效率和灵活性,因为它允许你以函数的方式直接调用这些操作,而不需要创建额外的层。当用print(net)输出时,nn.ReLU()会有对应的层,而F.ReLU()是没有输出的。

酒酿小圆子呀~ 1743

pytorch-nn.Module

pytorch nn.Module

wyw0000的博客 1258

nn.Module、nn.Sequential和torch.nn.parameter学习笔记

nn.Module、nn.Sequential和torch.nn.parameter是利用pytorch构建神经网络最重要的三个函数。搞清他们的具体用法是学习pytorch的必经之路。 目录nn.Modulenn.Sequentialtorch.nn.Parameter nn.Module nn.Module中,自定义层的步骤: 1.自定义一个Module的子类,实现两个基本的函数: (1)构造 init 函数 (2)层的逻辑运算函数,即正向传播的函数 2.在构造 init 函数中实现层的参数定义。 比如L

tangbiubiu的博客 3901
上一篇: PyTorch 1.0 系列学习教程(2): autograd
下一篇: 高等数学:第二章 导数与微分(1)导数的概念
gukedream
博客等级 码龄12年 480粉丝 87原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值