Pytorch怎么统计参数网络参数数量

其他教程   发布日期:2023年07月10日   浏览次数:539

这篇文章主要介绍了Pytorch怎么统计参数网络参数数量的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Pytorch怎么统计参数网络参数数量文章都会有所收获,下面我们一起来看看吧。

Pytorch统计参数网络参数数量

  1. def get_parameter_number(net):
  2. total_num = sum(p.numel() for p in net.parameters())
  3. trainable_num = sum(p.numel() for p in net.parameters() if p.requires_grad)
  4. return {'Total': total_num, 'Trainable': trainable_num}

Pytorch如何计算网络的参数量

本文以 Dense Block 为例,Pytorch 为 DL 框架,最终计算模块参数量方法如下:

  1. import torch
  2. import torch.nn as nn
  3. class Norm_Conv(nn.Module):
  4. def __init__(self,in_channel):
  5. super(Norm_Conv,self).__init__()
  6. self.layers = nn.Sequential(
  7. nn.Conv2d(in_channel,in_channel,3,1,1),
  8. nn.ReLU(True),
  9. nn.BatchNorm2d(in_channel),
  10. nn.Conv2d(in_channel,in_channel,3,1,1),
  11. nn.ReLU(True),
  12. nn.BatchNorm2d(in_channel),
  13. nn.Conv2d(in_channel,in_channel,3,1,1),
  14. nn.ReLU(True),
  15. nn.BatchNorm2d(in_channel))
  16. def forward(self,input):
  17. out = self.layers(input)
  18. return out
  19. class DenseBlock_Norm(nn.Module):
  20. def __init__(self,in_channel):
  21. super(DenseBlock_Norm,self).__init__()
  22. self.first_layer = nn.Sequential(nn.Conv2d(in_channel,in_channel,3,1,1),
  23. nn.ReLU(True),
  24. nn.BatchNorm2d(in_channel))
  25. self.second_layer = nn.Sequential(nn.Conv2d(in_channel*2,in_channel,3,1,1),
  26. nn.ReLU(True),
  27. nn.BatchNorm2d(in_channel))
  28. self.third_layer = nn.Sequential(
  29. nn.Conv2d(in_channel*3,in_channel,3,1,1),
  30. nn.ReLU(True),
  31. nn.BatchNorm2d(in_channel))
  32. def forward(self,input):
  33. output1 = self.first_layer(input)
  34. output2 = self.second_layer(torch.cat((output1,input),dim=1))
  35. output3 = self.third_layer(torch.cat((input,output1,output2),dim=1))
  36. return output3
  37. def count_param(model):
  38. param_count = 0
  39. for param in model.parameters():
  40. param_count += param.view(-1).size()[0]
  41. return param_count
  42. # Get Parameter number of Network
  43. in_channel = 128
  44. net1 = Norm_Conv(in_channel)
  45. print('Norm Conv parameter count is {}'.format(count_param(net1)))
  46. net2 = DenseBlock_Norm(in_channel)
  47. print('DenseBlock Norm parameter count is {}'.format(count_param(net2)))

最终结果如下

Norm Conv parameter count is 443520
DenseBlock Norm parameter count is 885888

以上就是Pytorch怎么统计参数网络参数数量的详细内容,更多关于Pytorch怎么统计参数网络参数数量的资料请关注九品源码其它相关文章!