神經網絡打印模型參數及參數名字和數量

神經網絡打印模型參數及參數名字和數量

在設計和優化神經網絡模型性能時,很多時候需要考慮模型的參數量和計算複雜度,下面一個栗子可以幫助我們快速查看模型的參數。
** 舉個栗子,如有錯誤,歡迎大家批評指正 **
本文鏈接:神經網絡打印模型參數及參數名字和數量
https://blog.csdn.net/leiduifan6944/article/details/103690228

exp:

import torch
from torch import nn


class Net(nn.Module):
	def __init__(self):
		super().__init__()
		self.fc1 = nn.Linear(3*4*4, 3*5*5)
		self.conv1 = nn.Sequential(
			nn.Conv2d(3, 4, 1, 1),		# conv1.0
			nn.BatchNorm2d(4),			# conv1.1
			nn.LeakyReLU(),				# conv1.2

			nn.Conv2d(4, 4, 3, 1),		# conv1.3
			nn.BatchNorm2d(4),			# conv1.4
			nn.LeakyReLU(),				# conv1.5
		)

		self.fc2 = nn.Linear(4*3*3, 10)

	def forward(self, entry):
		entry = entry.reshape(-1, 3*4*4)
		fc1_out = self.fc1(entry)
		fc1_out = fc1_out.reshape(-1, 3, 5, 5)
		conv1_out = self.conv1(fc1_out)
		conv1_out = conv1_out.reshape(-1, 4*3*3)
		fc2_out = self.fc2(conv1_out)

		return fc2_out


if __name__ == '__main__':
	x = torch.Tensor(2, 3, 4, 4)
	net = Net()

	out = net(x)
	print('%14s : %s' % ('out.shape', out.shape))
	print('---------------華麗麗的分隔線---------------')
	# -------------方法1--------------
	sum_ = 0
	for name, param in net.named_parameters():
		mul = 1
		for size_ in param.shape:
			mul *= size_							# 統計每層參數個數
		sum_ += mul									# 累加每層參數個數
		print('%14s : %s' % (name, param.shape))  	# 打印參數名和參數數量
		# print('%s' % param)						# 這樣可以打印出參數,由於過多,我就不打印了
	print('參數個數:', sum_)						# 打印參數量
	
	# -------------方法2--------------
	for param in net.parameters():
		print(param.shape)
		# print(param)

	# -------------方法3--------------
	params = list(net.parameters())
	for param in params:
		print(param.shape)
		# print(param)

以下是方法1的輸出效果:

(方法2和方法3沒貼出效果,個人比較喜歡用方法1,因爲可以看到當前打印的是哪一層網絡的參數)

     out.shape : torch.Size([2, 10])
---------------華麗麗的分隔線---------------
    fc1.weight : torch.Size([75, 48])
      fc1.bias : torch.Size([75])
conv1.0.weight : torch.Size([4, 3, 1, 1])
  conv1.0.bias : torch.Size([4])
conv1.1.weight : torch.Size([4])
  conv1.1.bias : torch.Size([4])
conv1.3.weight : torch.Size([4, 4, 3, 3])
  conv1.3.bias : torch.Size([4])
conv1.4.weight : torch.Size([4])
  conv1.4.bias : torch.Size([4])
    fc2.weight : torch.Size([10, 36])
      fc2.bias : torch.Size([10])
參數個數: 4225

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章