Pytorch:训练期间的中间测试

Pytorch: Intermediate testing during training

我如何在训练期间用验证数据测试我的 pytorch 模型? 我知道有一个函数 myNet.eval() 可以明显地切换任何 dropout 层,但它是否也阻止了梯度的累积?
另外,我将如何撤消 myNet.eval() 命令以继续培训?

如果有人有一些代码片段/玩具示例,我将不胜感激!

How can I test my pytorch model on validation data during training?

有很多示例在训练过程中的每个时期都有训练和测试步骤。一个简单的是 official MNIST example。由于 pytorch 不提供任何高级培训、验证或评分框架,您必须自己编写。通常这包括

  • 一个数据加载器(通常基于torch.utils.dataloader.Dataloader
  • 总轮数的主循环
  • 使用训练数据优化模型的train()函数
  • 一个 test()valid() 函数来衡量给定验证数据和度量模型的有效性

这也是您将在链接示例中找到的内容。

或者,您可以使用提供基本循环和验证工具的框架,这样您就不必一直自己实现所有内容。

  • tnt is torchnet for pytorch, supplying you with different metrics (such as accuracy) and abstraction of the train loop. See this MNIST example.
  • inferno and torchsample 尝试对与 Keras 非常相似的事物进行建模并提供一些验证工具
  • skorch 是 pytorch 的 scikit-learn 包装器,可让您使用 sklearn
  • 中的所有工具和指标

Also how would I undo the myNet.eval() command in order to continue with the training?

myNet.train() 或者,提供一个布尔值以在评估和训练之间切换:myNet.train(True) 用于训练模式。

I know that there is the function myNet.eval() which apparantly switches of any dropout layers, but is it also preventing the gradients from being accumulated?

它不会阻止渐变累积。

但我认为在测试期间,您确实想要忽略渐变。在那种情况下,您应该将网络的变量输入标记为volatile=True,这将节省一些时间和space用于前向计算。

Also how would I undo the myNet.eval() command in order to continue with the training?

myNet.train()