model.py
# 导入pytorch这个包
import torch.nn as nn
import torch.nn.functional as F
# 定义一个类,叫LeNeT,来自于nn.Module
class LeNet(nn.Module):
# 初始化
def __init__(self):
# super解决的是在一层一层调用父类时出现的问题,反正每次init的时候加上这句话准没错
super(LeNet, self).__init__()
# 定义卷积层,参数in_channels输入特征矩阵的深度(如果输入RBG彩色图像就为3),outchannels卷积核的个数,kernelsize卷积核的大小
self.conv1 = nn.Conv2d(3, 16, 5)
# 定义下采样层,2×2说明缩小为一半
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):
# output 28=(w-f+2p)/s+1=32(图像尺寸大小)-5(卷积核大小)+0(padding=0)/stride(步距为1)+1 = 28
x = F.relu(self.conv1(x)) # input(3, 32, 32) output(16, 28, 28)
x = self.pool1(x) # output(16, 14, 14) 上一个output的一半
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
import torch
input1 = torch.rand([32,3,32,32])
model = LeNet()
print(model)
output = model(input1)
train.py
import torch
import torchvision
import torch.nn as nn
from model import LeNet
import torch.optim as optim
import torchvision.transforms as transforms
# Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
# 50000张训练图片
train_set = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
# 导入训练数据集,batch_size 批次处理,shuffle是否打乱数据,默认true,
train_loader = torch.utils.data.DataLoader(train_set, batch_size=36,
shuffle=False, num_workers=0)
# 10000张验证图片
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)
# 吧val_loader转为可迭代的迭代器
val_data_iter = iter(val_loader)
val_image, val_label = val_data_iter.next()
# 定义分类
classes = ('plane', 'car', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
net = LeNet()
# 定义损失函数
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):
# get the inputs; data is a list of [inputs, labels]
# inputs表示训练的图片,labels表示图片的正确分类
inputs, labels = data
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
# outputs表示输出训练数据的分类结果
outputs = net(inputs)
# 训练结果和真实结果计算loss
loss = loss_function(outputs, labels)
# 损失反向传播
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
# 每500次打印输出
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 = (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')
save_path = './Lenet.pth'
# 训练模型存储
torch.save(net.state_dict(), save_path)