2024-09-29 12:34:47 发布
网友
我使用以下语句保存具有知识转移的VGG16:
torch.save(model.state_dict(), 'checkpoint.pth')
并使用以下语句重新加载:
州政府=装载焊炬('检查点.pth') 模型加载状态(州政府)
只要我重新加载VGG16模型,并使用以下代码为其提供与之前相同的设置,就可以实现此功能:
如何避免这种情况? 如何在不必重新加载VGG16和重新定义分类器的情况下重新加载模型?在
为什么不直接重新定义一个类似VGG16的模型呢? 查看vgg.py了解详细信息
class VGG_New(nn.Module): def __init__(self, features, num_classes=1000, init_weights=True): super(VGG, self).__init__() self.features = features # change here with you code self.classifier = nn.Sequential( nn.Linear(512 * 7 * 7, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, num_classes), ) if init_weights: self._initialize_weights() def forward(self, x): x = self.features(x) x = x.view(x.size(0), -1) x = self.classifier(x) return x def _initialize_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') if m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.normal_(m.weight, 0, 0.01) nn.init.constant_(m.bias, 0)
然后只为功能加载权重
为什么不直接重新定义一个类似VGG16的模型呢? 查看vgg.py了解详细信息
然后只为功能加载权重
^{pr2}$相关问题 更多 >
编程相关推荐