LeNet
- 网络结构
- 代码
-
- model.py
- train.py
- predict.py
网络结构
代码
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))
x = self.pool1(x)
x = F.relu(self.conv2(x))
x = self.pool2(x)
x = x.view(-1, 32 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
train.py
from model import LeNet
import torch
import torch.nn as nn
import torchvision as tv
import torchvision.transforms as transforms
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
trainset = tv.datasets.CIFAR10(
root='C:/Users/14251/Desktop/workspace/LeNet/data',
train=True,
transform=transform,
download=False)
trainloader = torch.utils.data.DataLoader(trainset,
batch_size=36,
shuffle=True,
num_workers=0)
testset = tv.datasets.CIFAR10(
root='C:/Users/14251/Desktop/workspace/LeNet/data',
train=False,
transform=transform,
download=False)
testloader = torch.utils.data.DataLoader(testset,
batch_size=10000,
shuffle=True,
num_workers=0)
testdata_iter = iter(testloader)
testdata, testlabel = testdata_iter.next()
net = LeNet()
loss_func = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(net.parameters(), lr=0.0001)
for epoch in range(5):
running_loss = 0
for step, data in enumerate(trainloader, start=0):
traindata, trainlabel = data
optimizer.zero_grad()
output = net(traindata)
loss = loss_func(output, trainlabel)
loss.backward()
optimizer.step()
running_loss += loss.item()
if step % 499 == 0:
with torch.no_grad():
output = net(testdata)
pred = torch.max(output, dim=1)[1]
accuracy = (pred == testlabel).sum().item() / testlabel.size(0)
print('[%d, %5d] train_loss: %.3f test_accuracy: %.3f' %
(epoch + 1, step + 1, running_loss / 500, accuracy))
running_loss = 0
print('Finished Training')
torch.save(net.state_dict(),
'C:/Users/14251/Desktop/workspace/LeNet/LeNet_dict.pth')
predict.py
from model import LeNet
import torch
import torchvision.transforms as transforms
from PIL import Image
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')
img = Image.open('C:/Users/14251/Desktop/workspace/LeNet/test2.jpg')
img = transform(img)
img = img.unsqueeze(dim=0)
net = LeNet()
net.load_state_dict(
torch.load('C:/Users/14251/Desktop/workspace/LeNet/LeNet_dict.pth'))
with torch.no_grad():
output = net(img)
predict = torch.max(output, dim=1)[1].item()
print(classes[int(predict)])