我训练了一个 Inception_v3
为我的任务。我有 3 节课。
训练后,我尝试测试我的训练模型,并使用以下代码加载我的模型:
model = models.inception_v3(pretrained=True, aux_logits=False)
model.fc = nn.Linear(model.fc.in_features, 3)
model.load_state_dict(torch.load(My Model Path.pth))
下载 预训练 Inception_v3,改变输出特征并在这个模型中加载我的权重。正如我在验证阶段所期望的那样,我获得了非常好的结果。
如果我使用相同的代码但预训练= 错误 测试进行得很糟糕。
model = models.inception_v3(pretrained=False, aux_logits=False)
model.fc = nn.Linear(model.fc.in_features, 3)
model.load_state_dict(torch.load(My Model Path.pth))
由于在我下载的模型中我加载了我的权重,因此预训练的 True 或 False 之间应该没有区别。有谁知道有什么变化?
最佳答案
pretrained=True
对 inception_v3
模型有额外的影响:它控制输入是否为
preprocessed according to the method with which it was trained on ImageNet
(源代码 here )。
当你设置
pretrained=False
时,如果你想让事情在测试时具有可比性,你还应该设置 transform_input=True
:model = models.inception_v3(pretrained=False, aux_logits=False, transform_input=True)
model.fc = nn.Linear(model.fc.in_features, 3)
model.load_state_dict(torch.load(My Model Path.pth))
如果您想知道,这是 preprocessing :def _transform_input(self, x: Tensor) -> Tensor:
if self.transform_input:
x_ch0 = torch.unsqueeze(x[:, 0], 1) * (0.229 / 0.5) + (0.485 - 0.5) / 0.5
x_ch1 = torch.unsqueeze(x[:, 1], 1) * (0.224 / 0.5) + (0.456 - 0.5) / 0.5
x_ch2 = torch.unsqueeze(x[:, 2], 1) * (0.225 / 0.5) + (0.406 - 0.5) / 0.5
x = torch.cat((x_ch0, x_ch1, x_ch2), 1)
return x
关于python - 在预训练模型中加载我的训练模型与在未预训练模型中加载之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64714933/