SoFunction
Updated on 2024-11-17

Example of PyTorch loading a pretrained model (pretrained)

The code to use the pre-trained model is as follows:

# Load pre-trained models
 resNet50 = models.resnet50(pretrained=True)
 ResNet50 = ResNet(Bottleneck, [3, 4, 6, 3], num_classes=2)

 # Read the parameters
 pretrained_dict = resNet50.state_dict()
 model_dict = ResNet50.state_dict()

 # Strike out keys in pretained_dict that don't belong in model_dict
 pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}

 # Update existing model_dict
 model_dict.update(pretrained_dict)

 # Load the state_dict that's really needed
 ResNet50.load_state_dict(model_dict)

This PyTorch loading pre-trained model example (pretrained) above is all I have to share with you, I hope it can give you a reference, and I hope you can support me more.