Verifying Access to Pre-Trained Models
PyTorch - Accessing Pre-Trained Models
Section titled “PyTorch - Accessing Pre-Trained Models”Before using a pre-trained model, let’s verify that we can access and load models provided by the PyTorch ecosystem, particularly the torchvision library which contains popular computer vision models.
Unlike the older Caffe2 approach where models were often specific files in an installation directory, PyTorch typically downloads pre-trained weights on demand when you request a pre-trained model for the first time. These weights are usually cached in a central directory (e.g., ~/.cache/torch/hub/checkpoints/ on Linux/macOS).
You can easily check available models and load one using torchvision.models. Let’s try loading the SqueezeNet 1.1 model, which was also available in Caffe2.
First, ensure you have torch and torchvision installed (see the Installation chapter). Then, run the following Python script:
import torchimport torchvision.models as models
# List some available models (optional)# print(dir(models))
print("Attempting to load pre-trained SqueezeNet 1.1 model...")
try: # Load the SqueezeNet 1.1 architecture with pre-trained weights # PyTorch will download weights if not already cached model = models.squeezenet1_1(pretrained=True)
# Set the model to evaluation mode (important for inference) model.eval()
print("Successfully loaded pre-trained SqueezeNet 1.1 model.") print("Model structure:") # Print the model structure (optional, can be very long) # print(model) print("Model ready for inference.")
except ImportError: print("Error: torchvision is not installed. Please install it using: pip install torchvision")except Exception as e: print(f"An error occurred: {e}") print("Please ensure you have an internet connection for the first download.")If the script runs successfully, you will see output confirming the model was loaded. You might see download progress the first time you run it.
Attempting to load pre-trained SqueezeNet 1.1 model...Successfully loaded pre-trained SqueezeNet 1.1 model.Model structure:Model ready for inference.This confirms that you can access and load pre-trained models from torchvision. Many other models like ResNet, VGG, MobileNet, etc., are available similarly by calling their respective functions in torchvision.models with pretrained=True.
Now you are ready to use a pre-trained model for a practical task like image classification.