LeNet-5中Params与MAC计算
文章目录
先给出LeNet-5网络的代码实现(基于PyTorch)
class LeNet(nn.Module):
def __init__(self):
super(LeNet, self).__init__()
# input_size=(1*28*28)
self.conv1 = nn.Sequential(
# in_channels, out_channels, kernel_size
# padding=2 保证输入输出尺寸相同
nn.Conv2d(1, 6, 5, padding=2),
# input_size=(6*28*28)
nn.ReLU(),
# output_size=(6*14*14)
nn.MaxPool2d(kernel_size=2, stride=2),
)
self.conv2 = nn.Sequential(
nn.Conv2d(6, 16, 5),
# input_size=(16*10*10)
nn.ReLU(),
# output_size=(16*5*5)
nn.MaxPool2d(2, 2)
)
self.fc1 = nn.Sequential(
nn.Linear(16*5*5, 120),
nn.ReLU()
)
self.fc2 = nn.Sequential(
nn.Linear(120, 84),
nn.ReLU()
)
self.fc3 = nn.Linear(84, 10)
# 定义前向传播过程,输入为x
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
# nn.Linear()的输入输出都是维度为一的值,
# 所以要把多维度的tensor展平成一维
x = x.view(x.size()[0], -1)
x = self.fc1(x)
x = self.fc2(x)
x = self.fc3(x)
return xLeNet-5网络计算量(MAC)和参数量(Weight)精算表
输入图像大小$1\times 28\times 28$

参数量的计算比较好理解,下面主要介绍下MAC的计算过程:
- 卷积层:$(C_{in}\times K^2+1)\times H\times W\times C_{out}$
其中$C_{in}$为输入通道数,$C_{out}$为输出通道数,$WH$为输出特征图的宽高,$K$为卷积核大小。
- 全连接层:$I\times O$
其中$I$为输入神经元数量,$O$为输出神经元数量。
乘积累加运算(Multiply Accumulate, MAC)是在数字信号处理器或一些微处理器中的特殊运算。实现此运算操作的硬件电路单元,被称为“乘数累加器”。这种运算的操作,是将乘法的乘积结果和累加器$a$的值相加,再存入累加器:$a\leftarrow a+b\times c$
代码实现
# pip install thop (now continously intergrated on Github actions)
# OR
# pip install --upgrade git+https://github.com/Lyken17/pytorch-OpCounter.git
from thop import profile
net = LeNet()
input = torch.randn(1, 1, 28, 28)
macs, params = profile(net, inputs=(input, ))
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论