深度学习第一章-LeNet搭建
基于PyTorch框架,本模型存放于目录:
E:\python文件\deep-learning-for-image-processing-master\pytorch_classification\Test1_official_demo
经卷积后的矩阵尺寸大小计算公式为:
N=(W-F+2P)/S+1
- 输入图片大小W×W
- Filter大小FXF
- 步长S
- padding的像素数P
1
2
3
4
5
6
7 import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision.transforms as transforms
from PIL import Image
一.设置运行设备:GPU运行
1 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") #确认运行设备为GPU |
二.下载数据集-CIFAR10
It has the classes:’airplane’,’automobile’,’bird’,’cat’,’deer’,dog’,’frog’,’horse’, ship’,’truck’.
The images in CIFAR-10 are of size 3x32x32
1.定义预处理函数
1 | transform = transforms.Compose( #预处理函数 |
2.分别下载训练集,测试集并加载
1 | # 50000张训练图片 |
3.设置一个数据迭代器
1 | val_data_iter = iter(val_loader) #将数据转换为迭代器 |
三.定义网络模型
- 张量的序列:(batch,channel,height,width)
1 | class LeNet(nn.Module): |
四.训练网络模型
1 | net = LeNet().to(device) #实例化神经网络模型 |
结果如下:
五.保存训练完成之后的模型参数文件
1 | save_path = './Lenet.pth' |
六.使用任意图片测试分类效果
- 此处在文件夹里面添加了一个文件名为“1.jpg”的飞机图片
1 | transform = transforms.Compose( |