Print PyTorch Model Summary in Python - Complete Guide

If you are working with PyTorch, you may find it useful to print a summary of your model. This can help you get a better understanding of the architecture and parameters of your model.

To print a PyTorch model summary in Python, you can use the `torchsummary` package. This package provides a simple way to print a summary of your model, including the number of parameters and the size of each layer.

To get started, you'll need to install the `torchsummary` package. You can do this using pip:

pip install torchsummary

Once you have the package installed, you can use it to print a summary of your model. Here's an example:

import torch
from torchsummary import summary

# Define your model
model = torch.nn.Sequential(
    torch.nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1),
    torch.nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1),
    torch.nn.MaxPool2d(kernel_size=2, stride=2),
    torch.nn.Linear(64*16*16, 10)

# Print the model summary
summary(model, (3, 32, 32))

In this example, we define a simple convolutional neural network (CNN) with two convolutional layers, a max pooling layer, and a fully connected layer. We then use the `summary` function to print a summary of the model.

The `summary` function takes two arguments: the model and the input size. In this case, we pass in an input size of `(3, 32, 32)`, which corresponds to a 32x32 RGB image.

When you run this code, you should see a summary of your model printed to the console. This will include information about each layer, including the input and output shapes, the number of parameters, and the size of the output tensor.

In summary, printing a PyTorch model summary in Python is a useful tool for understanding the architecture and parameters of your model. By using the `torchsummary` package, you can easily print a summary of your model in just a few lines of code.

Click to rate this post!
[Total: 0 Average: 0]

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information