深度学习第一章-LeNet搭建

深度学习第一章-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
2
3
4
5
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") #确认运行设备为GPU
'''定义了一个名字为Net的网络模型'''
net = Net().to(device) #实例化一个网络模型,并将网络模型在GPU上运算
'''定义训练方法'''
data,target=data.to(device),target.to(device) #将数据集添加到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
2
3
transform = transforms.Compose( #预处理函数
[transforms.ToTensor(), #将图片数据转换为张量
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) #进行标准化,分别为均值与标准差, #output[channel] = (input[channel] - mean[channel]) / std[channel]

2.分别下载训练集,测试集并加载

1
2
3
4
5
6
7
8
9
10
11
12
# 50000张训练图片
# 第一次使用时要将download设置为True才会自动去下载数据集
train_set = torchvision.datasets.CIFAR10(root='./data', train=True, #下载训练集集
download=False, transform=transform)
train_loader = torch.utils.data.DataLoader(train_set, batch_size=36, #加载训练集
shuffle=True, num_workers=0)
# 10000张验证图片
# 第一次使用时要将download设置为True才会自动去下载数据集
val_set = torchvision.datasets.CIFAR10(root='./data', train=False,
download=False, transform=transform)
val_loader = torch.utils.data.DataLoader(val_set, batch_size=5000,
shuffle=False, num_workers=0)

3.设置一个数据迭代器

1
2
3
val_data_iter = iter(val_loader) #将数据转换为迭代器
val_image, val_label = next(val_data_iter) #设置迭代器下的输入与输出
val_image, val_label = val_image.to(device), val_label.to(device) #移到GPU

三.定义网络模型

  • 张量的序列:(batch,channel,height,width)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class LeNet(nn.Module):
def __init__(self): #网络模型搭建
super(LeNet, self).__init__() #必要的初识化函数
self.conv1 = nn.Conv2d(3, 16, 5)
self.pool1 = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(16, 32, 5)
self.pool2 = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(32*5*5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)

def forward(self, x): #前向传播设置
x = F.relu(self.conv1(x)) # input(3, 32, 32) output(16, 28, 28)
x = self.pool1(x) # output(16, 14, 14)
x = F.relu(self.conv2(x)) # output(32, 10, 10)
x = self.pool2(x) # output(32, 5, 5)
x = x.view(-1, 32*5*5) # output(32*5*5),此处在进入全连接层时,需要将张量展平
x = F.relu(self.fc1(x)) # output(120)
x = F.relu(self.fc2(x)) # output(84)
x = self.fc3(x) # output(10)
return x

四.训练网络模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
net = LeNet().to(device) #实例化神经网络模型
loss_function = nn.CrossEntropyLoss() #设置损失函数为交叉熵函数
optimizer = optim.Adam(net.parameters(), lr=0.001) #设置参数更新方法

for epoch in range(5): # loop over the dataset multiple times

running_loss = 0.0 #损失率累加
for step, data in enumerate(train_loader, start=0):
inputs, labels = data # get the inputs; data is a list of [inputs, labels]
inputs, labels = inputs.to(device), labels.to(device) #移到GPU

optimizer.zero_grad() #梯度清零以防止梯度累计
outputs = net(inputs) #输入数据训练,得到预测值
loss = loss_function(outputs, labels) #计算损失值
loss.backward() #根据损失值进行反向传播,计算梯度
optimizer.step() #更新参数
running_loss += loss.item() #进行损失值累加

if step % 500 == 499: # print every 500 mini-batches
with torch.no_grad(): #在验证过程中不要计算损失梯度
outputs = net(val_image) # [batch, 10]
predict_y = torch.max(outputs, dim=1)[1]
accuracy = torch.eq(predict_y, val_label).sum().item() / val_label.size(0)

print('[%d, %5d] train_loss: %.3f test_accuracy: %.3f' %
(epoch + 1, step + 1, running_loss / 500, accuracy))
running_loss = 0.0

print('Finished Training')

结果如下:

pAEswe1.png

五.保存训练完成之后的模型参数文件

1
2
save_path = './Lenet.pth'
torch.save(net.state_dict(), save_path)

六.使用任意图片测试分类效果

  • 此处在文件夹里面添加了一个文件名为“1.jpg”的飞机图片
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
transform = transforms.Compose(
[transforms.Resize((32, 32)), #将图像分辨率改变
transforms.ToTensor(), #将图像数据变为张量形式
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) #标准化图像

classes = ('plane', 'car', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')

net = LeNet()
net.load_state_dict(torch.load('Lenet.pth')) #载入参数文件

im = Image.open('1.jpg')
im = transform(im) # [C, H, W] #调整图像
im = torch.unsqueeze(im, dim=0) # [N, C, H, W] #增添一个维度

with torch.no_grad():
outputs = net(im)
predict = torch.max(outputs, dim=1)[1].numpy()
print(classes[int(predict)])
-------------本文结束-------------