深入浅出Pytorch函数——torch.nn.Module

分类目录:《深入浅出Pytorch函数》总目录


torch.nn.Module是所有Pytorch中所有神经网络模型的基类,我们的神经网络模型也应该继承这个类。Modules可以包含其它Modules,也允许使用树结构嵌入他们,还可以将子模块赋值给模型属性。

实例

复制代码
import torch.nn as nn
import torch.nn.functional as F

class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.conv1 = nn.Conv2d(1, 20, 5)       # submodule: Conv2d
        self.conv2 = nn.Conv2d(20, 20, 5)

    def forward(self, x):
       x = F.relu(self.conv1(x))
       return F.relu(self.conv2(x))

通过上面方式赋值的submodule会被注册。当调用.cuda()的时候,submodule的参数也会转换为cuda Tensor。

函数

eval()

将模块设置为evaluation模式,相当于self.train(False)。这个函数仅当模型中有Dropout和BatchNorm时才会有影响。

复制代码
def eval(self: T) -> T:
        r"""Sets the module in evaluation mode.

        This has any effect only on certain modules. See documentations of
        particular modules for details of their behaviors in training/evaluation
        mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`,
        etc.

        This is equivalent with :meth:`self.train(False) <torch.nn.Module.train>`.

        See :ref:`locally-disable-grad-doc` for a comparison between
        `.eval()` and several similar mechanisms that may be confused with it.

        Returns:
            Module: self
        """
        return self.train(False)
相关推荐
lambo mercy1 分钟前
什么是LangGraph?
人工智能
用户614776737889 分钟前
从零搭出能回答"自己文档"的 RAG:179 行代码,成本不到 1 毛
人工智能
紧跟先前的步伐13 分钟前
Go AI Agent 实战 11|请求结构、响应结构与 JSON 解析
人工智能·ai·golang·json
用户0081283740214 分钟前
从零写一个扫雷:两个数组、一个坑,和三个后来加的功能
人工智能
zybsjn17 分钟前
Chrome 10 月 27 日剔除 eMudhra 根:3 万张证书的排查命令与迁移清单
人工智能·大模型
居里先生75220 分钟前
PDF 去水印开发实录:Form XObject、Identity-H 字体与 6 个对象层深坑
人工智能
零基础12323 分钟前
自进化(Self-evolving / RSI):让 AI 系统自己变强的机制与边界
人工智能
ZhengEnCi25 分钟前
ROS2 为啥要拆成二三十个节点?一台小车背后的真实结构
人工智能·机器人·自动驾驶
梯度下降的咖啡师28 分钟前
把上一篇的 Function Calling 套个 while,就是你的第一个 Agent
人工智能
爱新觉罗胜利30 分钟前
500M 激活逼近 3.3B:VLA 的容量到底该加在哪一层
人工智能