python - 在预训练模型中加载我的训练模型与在未预训练模型中加载之间的区别?

标签 python pytorch conv-neural-network

我训练了一个 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=Trueinception_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/

相关文章:

python - @unique 装饰器在 python 中有什么作用?

python - Python 中的循环切片

scikit-learn - 使用 pytorch 和 sklearn 对 MNIST 数据集进行交叉验证

keras - 名称错误 : name 'Model is not defined' -how to resolve this?

python - Tensorflow CNN 模型出现错误 "NaN loss during training."

python - matplotlib 不均匀组大小条形图并排

python - 计算字典中 get 方法返回第二个选项的次数

pytorch - `GPyTorch` 中的简单二维高斯过程拟合不佳

python - 对 pytorch 中的张量尺寸和批量大小感到困惑

machine-learning - 如何在 Torch 的 GPU 上将张量的元素限制/舍入到小数点后 4 位?