54.3_增加测试模式
54.3 增加测试模式
在使用Dropout的情况下,我们需要区分训练阶段和测试阶段。为此,可以继续使用在步骤18创建的禁用反向传播模式(withdezero.no_grad():)。首先,在dezero/core.py的Config类附近添加以下阴影部分的代码。
dezero/core.py
class Config: enable_backprop $=$ True train $=$ True
@contextlib.contextmanager
def using_config(name, value): old_value $=$ getattr(Config, name) setattr(Config, name, value) yield setattr(Config, name, old_value)
def test_mode(): return using_config('train', False)上面的代码在Config类中添加了类变量train。这个变量的默认值是True。另外在dezero/init.py中有一行代码是fromdezero.core import Config,由此其他文件可以引用dezero.Config.train。
之后增加了 test_mode 函数。通过与 with 语句相结合,我们能够只在代码块内将 Config.train 切换为 False。由于用户也要直接使用这个函数,所以dezero/init.py 中增加了代码 fromdezero.core import test_mode。这样用户可以通过 fromdezero import test_mode 导入 test_mode 函数。