[PYTHON] About the matter that torch summary can be really used when building a model with Pytorch

Introduction

I'm building my own model, and before I connect it to the fully connected layer, I always ask, "What are the features of the input?" You can understand the structure of the model by typing print (model) often, but you cannot check the size of the Feature Map. That's where the torch summary comes in handy.

Who is the torch summary?

Simply put, it's a you can see the size of the feature map.

How to use torch summary

First, make a model

This time I made the following simple model. I haven't written it until I classify it.

Convolution ➡︎BN➡︎ReLU➡︎pooling➡︎ Convolution ➡︎BN➡︎ReLU➡︎pooling➡︎ Convolution ➡︎ Global Average Pooling

                                                                                                                                     
import torch
import torch.nn as nn
   
class SimpleCNN(nn.Module):     
    def __init__(self):
        super(SimpleCNN,self).__init__()
 
        self.conv1 = nn.Conv2d(3,16,kernel_size=3,stride=1)
        self.bn1 = nn.BatchNorm2d(16)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d((2,2))
        self.conv2 = nn.Conv2d(16,32,kernel_size=3,stride=1)
        self.bn2 = nn.BatchNorm2d(32)
        self.conv3 = nn.Conv2d(32,64,kernel_size=3,stride=1)
        self.gap = nn.AdaptiveMaxPool2d(1)
  
    def forward(self,x):  
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x) 
        x = self.maxpool(x)
        x = self.conv2(x)
        x = self.bn2(x)
        x = self.relu(x)
        x = self.maxpool(x)
        x = self.conv3(x)
        x = self.gap(x)
   
        return x

Installation of torch summary

pip install torchsummary

torchsummary How to use

from torchsummary import summary
model = SimpleCNN()  
summary(model,(3,224,224)) # summary(model,(channels,H,W))

This time, I am trying to assume an image input size of 224x224. If you want to try other resolutions, change the values of H and W.

Summary output


----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1         [-1, 16, 222, 222]             448
       BatchNorm2d-2         [-1, 16, 222, 222]              32
              ReLU-3         [-1, 16, 222, 222]               0
         MaxPool2d-4         [-1, 16, 111, 111]               0
            Conv2d-5         [-1, 32, 109, 109]           4,640
       BatchNorm2d-6         [-1, 32, 109, 109]              64
              ReLU-7         [-1, 32, 109, 109]               0
         MaxPool2d-8           [-1, 32, 54, 54]               0
            Conv2d-9           [-1, 64, 52, 52]          18,496
AdaptiveMaxPool2d-10             [-1, 64, 1, 1]               0
================================================================
Total params: 23,680
Trainable params: 23,680
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.57
Forward/backward pass size (MB): 30.29
Params size (MB): 0.09
Estimated Total Size (MB): 30.95
----------------------------------------------------------------

It is quite convenient to be able to check the Shape of Output. I'm grateful that it also counts the number of parameters.

At the end

torchsummary is convenient, so please use it.

Recommended Posts

About the matter that torch summary can be really used when building a model with Pytorch
About the matter that the re.compiled object can be used for the re.match pattern
About the contents of wscript when building a D language environment like that with Waf
A timer (ticker) that can be used in the field (can be used anywhere)
Understand the probabilities and statistics that can be used for progress management with a python program
A memo when creating an environment that can be debugged with Lambda @ Edge for the time being
[Python] Code that can be written with brain death at the beginning when scraping as a beginner
A model that identifies the guitar with fast.ai
About the matter that localhost: 4040 cannot be accessed after running Spark with Docker
Format DataFrame data with Pytorch into a form that can be trained with NN
I made a familiar function that can be used in statistics with Python
Convert images from FlyCapture SDK to a form that can be used with openCV
Python knowledge notes that can be used with AtCoder
[Python] Introduction to web scraping | Summary of methods that can be used with webdriver
[Django] About users that can be used on template
[Django] Field names, user registration, and login methods that can be used in the User model
[Atcoder] [C ++] I made a test automation tool that can be used during the contest
Format summary of formats that can be serialized with gensim
Goroutine (parallel control) that can be used in the field
Goroutine that can be used in the field (errgroup.Group edition)
Scripts that can be used when using bottle in Python
Precautions that must be understood when building a PYTHON environment
I investigated the pretreatment that can be done with PyCaret
Let's make a diagram that can be clicked with IPython
I tried to expand the database so that it can be used with PES analysis software
[Python] A program that finds the maximum number of toys that can be purchased with your money
Make a Spinbox that can be displayed in Binary with Tkinter
I made a shuffle that can be reset (reverted) with Python
Make a currency chart that can be moved around with Plotly (2)
Make a Spinbox that can be displayed in HEX with Tkinter
Python standard module that can be used on the command line
Make a currency chart that can be moved around with Plotly (1)
Building a distributed environment with the Raspberry PI series (Part 1: Summary of availability of diskless clients by model)
I created a template for a Python project that can be used universally
Acoustic signal processing module that can be used with Python-Sounddevice ASIO [Application]
The LXC Web Panel that can operate LXC with a browser was wonderful
Hide the warning that zsh can be used by default on Mac
Create a web app that can be easily visualized with Plotly Dash
Mathematical optimization that can be used for free work with Python + PuLP
Draw a graph that can be moved around with HoloViews and Bokeh
I made a simple timer that can be started from the terminal
Acoustic signal processing module that can be used with Python-Sounddevice ASIO [Basic]
I wanted to quickly create a mail server that can be used freely with postfix + dovecot on EC2
[Python3] Code that can be used when you want to cut out an image in a specific size
It seems that cancelall childorders can be used to cancel all parent orders (special orders) with the bitflyer API
[Python] Creating a tool that can list, select, and execute python files with tkinter & about the part that got caught
Article that can be a human resource who understands and masters the mechanism of API (with Python code)
[Python3] Code that can be used when you want to change the extension of an image at once
A memo for making a figure that can be posted to a journal with matplotlib
About the matter that softmax is not needed at the end of Torchvision model.
If "can not be used when making a PIE object" appears in make
I tried to summarize the operations that are likely to be used with numpy-stl
How to install a Python library that can be used by pharmaceutical companies
[Hackathon] About making a tool that can be CD on Raspberry Pi [Convenient tool]
A story about making an x86 bootloader that can boot vmlinux with Rust
"Gazpacho", a scraping module that can be used more easily than Beautiful Soup