Pytorch学习笔记:model.train()和model.eval()


前言

训练时的model.train()和测试时的model.eval()分别做了什么?


1.model.train()

源码如下:

def train(self: T, mode: bool = True) -> T:
    r"""Sets the module in training 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.

    Args:
        mode (bool): whether to set training mode (``True``) or evaluation
                     mode (``False``). Default: ``True``.

    Returns:
        Module: self
    """
    self.training = mode
    for module in self.children():
        module.train(mode)
    return self

2.model.eval()

源码如下:

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>`.

    Returns:
        Module: self
    """
    return self.train(False)

总结

提示:这里对文章进行总结:

简单来说,是设置了训练或者测试模式,定义模型是否需要学习。对部分层有影响,如Dropout和BN。具体影响如下:
Dropout: 训练过程中,为防止模型过拟合,增加其泛化性,会随机屏蔽掉一些神经元,相当于输入每次走过不同的“模型”。测试模式时,所有神经元共同作用,类似于boosting。
BN: 训练过程中,模型每次处理一个minibatch数据,BN根据一个minibatch来计算mean和std后做归一化处理,这也是为什么模型的性能和minibatch的大小关系很大(后续也有系列文章来解决BN在小minibatch下表现不佳的问题)。测试时,BN会利用训练时得到的参数来处理测试数据。如果不设置model.eval(),输入单张图像,会报错。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值