深入浅出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)
相关推荐
Mister Leon2 分钟前
Nvidia Orin AGX实战之从量化到蒸馏:在 Orin 上落地的大模型压缩实战
人工智能·算法·机器学习
Latchh5 分钟前
iLovePDF免费版能批量压缩吗?4款替代对比2026
图像处理·人工智能·计算机视觉·音视频
云和数据.ChenGuang10 分钟前
LangChain 实战指南:从入门到构建智能应用
开发语言·人工智能·python·langchain
IT_陈寒12 分钟前
Vite性能优化完全指南
前端·人工智能·后端
一条泥憨鱼14 分钟前
AI Agent 安全实践:从 MCP 工具调用到 Java 权限校验
java·人工智能·安全
东方佑15 分钟前
用先验重构线性注意力:为什么它至少比普通线性注意力更接近标准注意力
人工智能·机器学习·重构
lucas_AI18 分钟前
Read-Parse-Describe:文档解析终于把「图里画了什么」也写进结果了
人工智能
aneasystone本尊22 分钟前
学习大模型训练的目标函数:Next Token Prediction
人工智能
星核0penstarry22 分钟前
## 一、为什么 Spark UDF 越来越成为瓶颈
人工智能·api·ai编程·gpu·灰度发布·ai 智能体重写·等价性测试
中空板生产 线25 分钟前
现代中空板的发展趋势
人工智能