model.py
import torch.nn as nn
import torch.nn.functional as F
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),行数batch_size=32,列数32*5*5,-1表示自适应
x = F.relu(self.fc1(x)) # output(120)
x = F.relu(self.fc2(x)) # output(84)
x = self.fc3(x) # output(10)
return x
if __name__ == '__main__':
import torch
input=torch.rand([32,3,32,32])
model=LeNet()
print(model)
output=model(input)
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
def main():
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
#数据预处理,加载的是CIFAR10数据集,比较标准,预处理比较简单
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
# 50000张训练图片
# 第一次使用时要将download设置为True才会自动去下载数据集
#直接调用官方提供的对CIFAR10数据集的加载库,不用再自己写加载数据集的脚本
#加载后对数据进行预处理操作
train_set = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
#torch.utils.data.DataLoader 用于加载和批处理数据。它提供了对数据集的迭代访问,并支持并行加载数据。
#方便地对训练数据进行批处理,以提高训练效率,并且可以自动化地处理数据加载和预处理的过程,
#具体是怎么对输入数据集进行提取的,后面定义数据集时候再根据具体代码理解,这个是直接用的CIFAR类
#感兴趣可以看CIFAR数据集加载的定义
train_loader = torch.utils.data.DataLoader(train_set, batch_size=36,
shuffle=True, num_workers=0)
# 10000张验证图片
# 第一次使用时要将download设置为True才会自动去下载数据集
#CIFAR10数据集的训练集,验证集下载还是分开的
val_set = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=transform)
val_loader = torch.utils.data.DataLoader(val_set, batch_size=5000,
shuffle=False, num_workers=0)
#iter(val_loader)将验证数据加载器 val_loader 转换为一个迭代器对象 val_data_iter
#next(val_data_iter) 从迭代器中获取下一个元素,也就是验证数据集中的下一个批次数据。
#这个操作将返回一个元组,其中 val_image 是验证图像数据的批次,val_label 是相应的标签数据的批次。
#这个在epoch训练过程中,能从这里直接更新,这个用法很奇妙
val_data_iter = iter(val_loader)
val_image, val_label = next(val_data_iter)
#验证数据没必要放到gpu上
val_image, val_label =val_image.to(device), val_label.to(device)
# classes = ('plane', 'car', 'bird', 'cat',
# 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
#注意要把模型直接移到device上还要直接赋值给模型
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):
# get the inputs; data is a list of [inputs, labels]
inputs, labels = data
inputs,labels=inputs.to(device),labels.to(device)
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = loss_function(outputs, labels)
loss.backward()
optimizer.step()
# print statistics
#loss是一个torch.Tensor类型的标量值,代表了当前批次的损失。loss.item()方法用于获取该标量张量的Python数值
running_loss += loss.item()
if step % 500 == 499: # print every 500 mini-batches
with torch.no_grad():
outputs = net(val_image) # [batch, 10]
#torch.max(outputs, dim=1)[1]返回了每个样本在预测分数中的最大值所对应的类别索引,也就是模型预测的类别
"""
torch.eq(predict_y, val_label)会比较predict_y和val_label两个张量的对应元素是否相等,
返回一个布尔型的张量。通过调用.sum().item(),我们可以计算相等元素的总数,也就是预测正确的样本数。
"""
#torch.max() 函数返回一个元组,其中第一个元素是最大值的张量,第二个元素是最大值所在的索引张量
#dim=1表示沿着[batch, 10] num_classes的维度
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')
save_path = './Lenet.pth'
torch.save(net.state_dict(), save_path)
if __name__ == '__main__':
main()
predict.py
import torch
import torchvision.transforms as transforms
from PIL import Image
from model import LeNet
def main():
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
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'))
net=net.to(device)
im = Image.open('1.jpg')
im = transform(im) # [C, H, W]
im = torch.unsqueeze(im, dim=0) # [N, C, H, W]
im=im.to(device)
with torch.no_grad():
outputs = net(im)
predict = torch.max(outputs, dim=1)[1]
print(classes[int(predict)])
if __name__ == '__main__':
main()