?项目复现?|?项目复现?基于CIFAR-10+LeNet的训练实现

环境要求pytorch
基于pytorch深度学习框架,利用数据集CIFAR-10,在网络lenet5上进行 训练。
?项目复现?|?项目复现?基于CIFAR-10+LeNet的训练实现
文章图片

在torch中datasets可直接加载,所以不用单独下载。
Step1:在pycharm中写入lenet5main.py 写入如下代码,用来下载数据集

#cifar10数据集+LeNet10网络实现训练import torch #DataLoader可加载多个 from torch.utils.data import DataLoader from torchvision import datasets from torchvision import transformsdef datadownload(): batchsz=32 #一次加载一张 cifar_train=datasets.CIFAR10('cifar',True,transform=transforms.Compose([ transforms.Resize((32,32)), transforms.ToTensor() ]),download=True) cifar_train=DataLoader(cifar_train,batch_size=batchsz,shuffle=True)cifar_test = datasets.CIFAR10('cifar', False, transform=transforms.Compose([ transforms.Resize((32, 32)), transforms.ToTensor() ]), download = True) cifar_test = DataLoader(cifar_test, batch_size=batchsz, shuffle=True)#测试数据 #利用iter进行迭代,打印出shape x,label=iter(cifar_train).next() print('x:',x.shape,'label:',label.shape)if __name__ == '__main__': datadownload()

下载后
?项目复现?|?项目复现?基于CIFAR-10+LeNet的训练实现
文章图片

Step2:创建lenet5.py 主要是卷积网络lenet5的网络结构
#cifar10数据集+LeNet5网络训练 import torch from torch import nn from torch.nn import functional as Fclass Lenet5(nn.Module): def __init__(self): super(Lenet5, self).__init__() #输入二维图像,先经过俩层卷积层到池化层,再经过全连接层,最后使用softmax分类作为输出层 self.conv_unit=nn.Sequential( #x输入图像统一归一化为32*32输出是6 nn.Conv2d(3,6,kernel_size=5,stride=1,padding=0), nn.AvgPool2d(kernel_size=2,stride=2,padding=0),nn.Conv2d(6, 16, kernel_size=5, stride=1, padding=0), nn.AvgPool2d(kernel_size=2, stride=2, padding=0),) #隐藏层 #第6层全连接层 self.fc_unit=nn.Sequential( nn.Linear(16*5*5,120), nn.ReLU(), nn.Linear(120,84), nn.ReLU(), nn.Linear(84,10) )#分类问题使用交叉熵 #self.criteon=nn.CrossEntropyLoss()def forward(self,x): batchsz=x.size(0) x=self.conv_unit(x) x=x.view(batchsz,16*5*5) logits=self.fc_unit(x)#pred=F.softmax(logits,dim=1) #loss=self.criteon(logits,y) return logitsdef main(): net=Lenet5() #调用主类方法 tmp = torch.randn(2, 3, 32, 32) out = net(tmp) print('lenet5 out:', out.shape)if __name__ == '__main__': main()

Step3:填补lenet5main.py内容
#利用cifar10数据集+LeNet5网络进行训练 #构建主函数 import torch #DataLoader可加载多个数据 from torch.utils.data import DataLoader from torchvision import datasets from torchvision import transforms from torch import nn,optim from LeNET5.lenet5 import Lenet5def main(): batchsz=32 #一次加载一张 cifar_train=datasets.CIFAR10('cifar',True,transform=transforms.Compose([ transforms.Resize((32,32)), transforms.ToTensor() ]),download=True) cifar_train=DataLoader(cifar_train,batch_size=batchsz,shuffle=True)cifar_test = datasets.CIFAR10('cifar', False, transform=transforms.Compose([ transforms.Resize((32, 32)), transforms.ToTensor() ]), download = True) cifar_test = DataLoader(cifar_test, batch_size=batchsz, shuffle=True)#测试数据 #利用iter进行迭代,打印出shape #x,label=iter(cifar_train).next() #print('x:',x.shape,'label:',label.shape)# 使用cpu计算,如果有cuda,可用cuda device = torch.device('cpu') model=Lenet5().to(device) criteon=nn.CrossEntropyLoss() optimizer=optim.Adam(model.parameters(),lr=1e-3) print(model)for epoch in range(1000):model.train() for batchidx,(x,label) in enumerate(cifar_train): x,label=x.to(device),label.to(device) logits=model(x) loss=criteon(logits,label)optimizer.zero_grad() loss.backward() optimizer.step()print(epoch,loss.item())model.eval() with torch.no_grad(): #test total_correct=0 total_num=0 for x,label in cifar_test: x, label = x.to(device), label.to(device) logits = model(x) #在1维上最大的一个值 pred=logits.argmax(dim=1) total_correct+=torch.eq(pred,label).float().sum().item() total_num+=x.size(0)acc=total_correct/total_num print(epoch,acc)print(epoch,loss.item())if __name__ == '__main__': main()

【?项目复现?|?项目复现?基于CIFAR-10+LeNet的训练实现】结果:
?项目复现?|?项目复现?基于CIFAR-10+LeNet的训练实现
文章图片





    推荐阅读