深入浅出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)
相关推荐
黎阳之光5 分钟前
黎阳之光核工厂202应急管控平台|全域实景孪生,筑牢核安全最后一道防线
大数据·人工智能·算法·安全·数字孪生
小程故事多_8012 分钟前
破局AI Agent落地困境,Harness六大组件全解析与实践启示
人工智能·自动化·ai编程
深念Y15 分钟前
感知机 ≈ 可学习的逻辑门?聊聊激活函数与二元分类的本质
人工智能·学习·分类·感知机·激活函数·逻辑门·二元分类
LaughingZhu16 分钟前
Product Hunt 每日热榜 | 2026-04-18
人工智能·经验分享·深度学习·神经网络·产品运营
Raink老师18 分钟前
【AI面试临阵磨枪】大模型中的温度(Temperature)、Top-p、Top-k、Repetition penalty 分别控制什么?
人工智能·ai 面试
liu****31 分钟前
LangGraph-AI应用开发框架(三)
人工智能·python·langchain·langgraph·大模型部署
Only you, only you!33 分钟前
Openclaw本地部署,开启养龙虾模式
人工智能·vllm·gent
克里普crirp38 分钟前
短波通信的可用频率计算方法
人工智能·算法·机器学习
px不是xp40 分钟前
DeepSeek API集成:让小程序拥有AI大脑
javascript·人工智能·小程序
hqyjzsb1 小时前
AI培训课程怎么设计才有效?
人工智能·职场和发展·aigc·产品经理·学习方法·业界资讯·设计语言