LeNet5学习(2024.3.4)
![](https://i-blog.csdnimg.cn/blog_migrate/e399a2f8f8eaf2e628ba25849990e36d.png)
代码复现
1.导入库
# 导入torch包
import torch
import torch.nn as nn
import torch.nn.functional as F
2.构建网络,利用nn.Model继承搭建LenNet网络
# 构建网络,继承nn.Module
class LeNet(nn.Module):
# 初始化函数
def __init__(self,):
# 多继承,把Model里所有的东西继承过来,以供LeNet使用
super(LeNet, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5)
self.conv2 = nn.Conv2d(in_channels=6, out_channels=16, kernel_size=5)
self.fc1 = nn.Linear(16*5*5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
# 前向传播函数
def forward(self, x):
#处理的是tensor数据[batch, channel, H, W]
x = self.conv1(x)
x = F.relu(x)
x = F.max_pool2d(x,(2,2))
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x,(2,2))
# 需要把tensor拉平,即16*5*5 -> 400*1,行数和batch生成因此用-1保持不变,[1:]将batch去掉,后面的channel和H和W拉平
x = x.view(-1,x.size()[1:], num1())
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
3.测试打印输出
model = LeNet()
print(model)
![](https://i-blog.csdnimg.cn/blog_migrate/4443620ecaf4c995ab536d5e0aa5628e.png)