我的博客

pytorch CIFAR10 分类 - 教程 demo 改写

目录

主要修改了来的数据加载部分,目前还没有归一化

网络定义(和教程一致)

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
import torch
import torch.nn as nn
import torch.nn.functional as F


class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)

def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x


net = Net()

数据加载和训练

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
30
31
32
33
import pickle
import matplotlib.pyplot as plt
import numpy as np

def unpickle(file):
with open(file, 'rb') as fo:
dict = pickle.load(fo, encoding='bytes')
return dict

import torch.optim as optim

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

for i in range(1, 6):
d = unpickle('data_batch_%d' % i)
epoch = i
running_loss = 0
for i in range(len(d[b'data'])):
raw = torch.tensor(d[b'data'][i], dtype=torch.float)
label = d[b'labels'][i]
inputx = raw.reshape(1, 3, 32, 32)
outputs = net(inputx)
loss = criterion(outputs, torch.tensor([label,]))
loss.backward()
optimizer.step()

# print statistics
running_loss += loss.item()
if i % 2000 == 1999: # print every 2000 mini-batches
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 2000))
running_loss = 0.0

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
correct = 0
total = 0
d = unpickle('test_batch')
with torch.no_grad():
for i in range(len(d[b'data'])):
raw = torch.tensor(d[b'data'][i], dtype=torch.float)
label = d[b'labels'][i]
inputx = raw.reshape(1, 3, 32, 32)
outputs = net(inputx)
outputs = net(inputx)
_, predicted = torch.max(outputs.data, 1)
total += 1
if predicted.item() == label:
correct += 1

print('Accuracy of the network on the 10000 test images: %d %%' % (
100 * correct / total))

输出:Accuracy of the network on the 10000 test images: 10 %

评论无需登录,可以匿名,欢迎评论!