深入浅出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)。这个函数仅当模型中有DropoutBatchNorm时才会有影响。

复制代码
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)
相关推荐
老张的码几秒前
飞书 × OpenClaw 接入指南
人工智能·后端
jerrywus42 分钟前
为什么每个程序员都应该试试 cmux:AI 加持的终端效率革命
前端·人工智能·claude
孟祥_成都1 小时前
AI 术语满天飞?90% 的人只懂名词,不懂为什么!
前端·人工智能
机器之心1 小时前
高德纳:「震惊!震惊!」Claude破解《计算机程序设计艺术》难题
人工智能·openai
石臻臻的杂货铺1 小时前
GPT-5.4 发布:Computer Use 超越人类,Tool Search 让 Agent 用工具省了一半 token
人工智能
gustt1 小时前
使用 LangChain 构建 AI 代理:自动化创建 React TodoList 应用
人工智能·llm·agent
碳基沙盒1 小时前
OpenClaw 浏览器自动化配置完全指南
人工智能
Baihai_IDP2 小时前
在 Anthropic 的这两年,我学会了 13 件事
人工智能·程序员·llm
IT_陈寒3 小时前
JavaScript这5个隐藏技巧,90%的开发者都不知道!
前端·人工智能·后端