VGG16 预测中的随机性

Randomness in VGG16 prediction

我正在使用开箱即用的 pytorch 中可用的 VGG-16 网络来预测一些图像索引。我发现对于同一个输入文件,如果我预测多次,我会得到不同的结果。这对我来说似乎违反直觉。一旦预测了权重(因为我使用的是预训练模型),任何步骤都不应该有任何随机性,因此具有相同输入文件的多个 运行 应该 return 相同的预测。

这是我的代码:

import torch
import torchvision.models as models
VGG16 = models.vgg16(pretrained=True)
def VGG16_predict(img_path):
  transformer = transforms.Compose([transforms.CenterCrop(224),transforms.ToTensor()])
  data = transformer(Image.open(img_path))
  output = softmax(VGG16(data.unsqueeze(0)), dim=1).argmax().item()
  return output # predicted class index
VGG16_predict(image) 

这是图片

回想一下,许多模块有两种状态用于训练和评估:"Some models use modules which have different training and evaluation behavior, such as batch normalization. To switch between these modes, use model.train() or model.eval() as appropriate. See train() or eval() for details." (https://pytorch.org/docs/stable/torchvision/models.html)

在这种情况下,分类器层包括 dropout,它在训练期间是随机的。 运行 VGG16.eval() 如果您希望评估为 non-random。