0


PyTorch 打印模型结构、输出维度和参数信息(torchsummary)

使用 PyTorch 深度学习搭建模型后,如果想查看模型结构,可以直接使用 print(model) 函数打印。但该输出结果不是特别直观,查阅发现有个能输出类似 keras 风格 model.summary() 的模型可视化工具。这里记录一下方便以后查阅。

PyTorch 打印模型结构、输出维度和参数信息(torchsummary)

安装 torchsummary

  1. pip install torchsummary

输出网络信息

summary函数介绍

  1. model

:网络模型

  1. input_size

:网络输入图片的shape,这里不用加batch_size进去

  1. batch_size

:batch_size参数,默认是-1

  1. device

:在GPU还是CPU上运行,默认是cuda在GPU上运行,如果想在CPU上执行将参数改为CPU即可

  1. import torch
  2. import torch.nn as nn
  3. from torchsummary import summary
  4. classShallow_ConvNet(nn.Module):def__init__(self, in_channel, conv_channel_temp, kernel_size_temp, conv_channel_spat, kernel_size_spat,
  5. pooling_size, pool_stride_size, dropoutRate, n_classes, class_kernel_size):super(Shallow_ConvNet, self).__init__()
  6. self.temp_conv = nn.Conv2d(in_channels=in_channel,
  7. out_channels=conv_channel_temp,
  8. kernel_size=(1, kernel_size_temp),
  9. stride=1,
  10. bias=False)
  11. self.spat_conv = nn.Conv2d(in_channels=conv_channel_temp,
  12. out_channels=conv_channel_spat,
  13. kernel_size=(kernel_size_spat,1),
  14. stride=1,
  15. bias=False)
  16. self.bn = nn.BatchNorm2d(num_features=conv_channel_spat)# slef.act_conv = x*x
  17. self.pooling = nn.AvgPool2d(kernel_size=(1, pooling_size),
  18. stride=(1, pool_stride_size))# slef.act_pool = log(max(x, eps))
  19. self.dropout = nn.Dropout(p=dropoutRate)
  20. self.class_conv = nn.Conv2d(in_channels=conv_channel_spat,
  21. out_channels=n_classes,
  22. kernel_size=(1, class_kernel_size),
  23. bias=False)
  24. self.softmax = nn.Softmax(dim=1)defsafe_log(self, x):""" Prevents :math:`log(0)` by using :math:`log(max(x, eps))`."""return torch.log(torch.clamp(x,min=1e-6))defforward(self, x):# input shape (batch_size, C, T)iflen(x.shape)isnot4:
  25. x = torch.unsqueeze(x,1)# input shape (batch_size, 1, C, T)
  26. x = self.temp_conv(x)
  27. x = self.spat_conv(x)
  28. x = self.bn(x)
  29. x = x*x # conv_activate
  30. x = self.pooling(x)
  31. x = self.safe_log(x)# pool_activate
  32. x = self.dropout(x)
  33. x = self.class_conv(x)
  34. x= self.softmax(x)
  35. out = torch.squeeze(x)return out
  36. ###============================ Initialization parameters ============================###
  37. channels =44
  38. samples =534
  39. in_channel =1
  40. conv_channel_temp =40
  41. kernel_size_temp =25
  42. conv_channel_spat =40
  43. kernel_size_spat = channels
  44. pooling_size =75
  45. pool_stride_size =15
  46. dropoutRate =0.3
  47. n_classes =4
  48. class_kernel_size =30defmain():input= torch.randn(32,1, channels, samples)
  49. model = Shallow_ConvNet(in_channel, conv_channel_temp, kernel_size_temp, conv_channel_spat, kernel_size_spat,
  50. pooling_size, pool_stride_size, dropoutRate, n_classes, class_kernel_size)
  51. out = model(input)print('===============================================================')print('out', out.shape)print('model', model)
  52. summary(model=model, input_size=(1,channels,samples), batch_size=32, device="cpu")if __name__ =="__main__":
  53. main()

输出:

  1. out torch.Size([32,4])
  2. model Shallow_ConvNet((temp_conv): Conv2d(1,40, kernel_size=(1,25), stride=(1,1), bias=False)(spat_conv): Conv2d(40,40, kernel_size=(44,1), stride=(1,1), bias=False)(bn): BatchNorm2d(40, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(pooling): AvgPool2d(kernel_size=(1,75), stride=(1,15), padding=0)(dropout): Dropout(p=0.3, inplace=False)(class_conv): Conv2d(40,4, kernel_size=(1,30), stride=(1,1), bias=False)(softmax): Softmax(dim=1))----------------------------------------------------------------
  3. Layer (type) Output Shape Param #================================================================
  4. Conv2d-1[32,40,44,510]1,000
  5. Conv2d-2[32,40,1,510]70,400
  6. BatchNorm2d-3[32,40,1,510]80
  7. AvgPool2d-4[32,40,1,30]0
  8. Dropout-5[32,40,1,30]0
  9. Conv2d-6[32,4,1,1]4,800
  10. Softmax-7[32,4,1,1]0================================================================
  11. Total params:76,280
  12. Trainable params:76,280
  13. Non-trainable params:0----------------------------------------------------------------
  14. Input size (MB):2.87
  15. Forward/backward pass size (MB):229.69
  16. Params size (MB):0.29
  17. Estimated Total Size (MB):232.85----------------------------------------------------------------

AttributeError: ‘tuple’ object has no attribute ‘size’

旧的summary加入LSTM之类的会报错,需要用新的summarry

  1. pip install torchinfo
  1. from torchinfo import summary
  2. defmain():input= torch.randn(32, window_size, channels, samples)
  3. model = Cascade_Conv_LSTM(in_channel, out_channel_conv1, out_channel_conv2, out_channel_conv3, kernel_conv123, stride_conv123, padding_conv123,
  4. fc1_in, fc1_out, dropoutRate1, lstm1_in, lstm1_hidden, lstm1_layer, lstm2_in, lstm2_hidden, lstm2_layer, fc2_in, fc2_out, dropoutRate2,
  5. fc3_in, n_classes)# model = model.to('cuda:1')# input = torch.from_numpy(input).to('cuda:1').to(torch.float32).requires_grad_()
  6. out = model(input)print('===============================================================')print('out', out.shape)print('model', model)
  7. summary(model=model, input_size=(32,10,channels,samples), device="cpu")if __name__ =="__main__":
  8. main()
  1. ==========================================================================================
  2. Layer (type:depth-idx) Output Shape Param #==========================================================================================
  3. Cascade_Conv_LSTM [32,4]--
  4. ├─Sequential:1-1[320,32,10,11]--
  5. └─Conv2d:2-1[320,32,10,11]288
  6. └─ELU:2-2[320,32,10,11]--
  7. ├─Sequential:1-2[320,64,10,11]--
  8. └─Conv2d:2-3[320,64,10,11]18,432
  9. └─ELU:2-4[320,64,10,11]--
  10. ├─Sequential:1-3[320,128,10,11]--
  11. └─Conv2d:2-5[320,128,10,11]73,728
  12. └─ELU:2-6[320,128,10,11]--
  13. ├─Sequential:1-4[320,1024]--
  14. └─Linear:2-7[320,1024]14,418,944
  15. └─ELU:2-8[320,1024]--
  16. ├─Dropout:1-5[320,1024]--
  17. ├─LSTM:1-6[32,10,1024]8,396,800
  18. ├─LSTM:1-7[32,10,1024]8,396,800
  19. ├─Sequential:1-8[32,1024]--
  20. └─Linear:2-9[32,1024]1,049,600
  21. └─ELU:2-10[32,1024]--
  22. ├─Dropout:1-9[32,1024]--
  23. ├─Linear:1-10[32,4]4,100
  24. ├─Softmax:1-11[32,4]--==========================================================================================
  25. Total params:32,358,692
  26. Trainable params:32,358,692
  27. Non-trainable params:0
  28. Total mult-adds (G):13.28==========================================================================================
  29. Input size (MB):0.14
  30. Forward/backward pass size (MB):71.21
  31. Params size (MB):129.43
  32. Estimated Total Size (MB):200.78==========================================================================================

本文转载自: https://blog.csdn.net/qq_41990294/article/details/128770708
版权归原作者 梁小憨憨 所有, 如有侵权,请联系我们删除。

“PyTorch 打印模型结构、输出维度和参数信息(torchsummary)”的评论:

还没有评论