Pytorch实现CIFAR10之训练模型

示例代码:

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

lr = 0.001
best_acc = 0 # best test accuracy
epochs = 20
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters(), lr=lr, weight_decay=5e-4)
# Training
def train():
for epoch in range(epochs):
print('\nEpoch: {}'.format(epoch + 1))
train_loss = 0
correct = 0
total = 0
for step, (inputs, targets) in enumerate(trainloader):

outputs = net(inputs)[0]
loss = criterion(outputs, targets)

optimizer.zero_grad()
loss.backward()
optimizer.step()

train_loss += loss.item()

_, predicted = outputs.max(1)
total += targets.size(0)
correct += predicted.eq(targets).sum().item()

if step % 50 == 0:
print("step:{} ".format(step))
print("Loss:%.4f " % (train_loss / (step + 1)))
print("train Accuracy: %4f" % (100.*correct/total))

print('Finished Training')


def test():
net.eval()
test_loss = 0
correct = 0
total = 0
with torch.no_grad():
for step, (inputs, targets) in enumerate(testloader):
outputs, _ = net(inputs)
loss = criterion(outputs, targets)

test_loss += loss.item()
_, predicted = outputs.max(1)
total += targets.size(0)
correct += predicted.eq(targets).sum().item()
if step % 50 == 0:
print("step:{} ".format(step))
print("Loss:%.4f " % (test_loss / (step + 1)))
print("Test Accuracy: %4f" % (100.*correct/total))
print("TEST Finished")

转载请注明:Seven的博客

本文标题:Pytorch实现CIFAR10之训练模型

文章作者:Seven

发布时间:2018年09月15日 - 00:00:00

最后更新:2018年12月11日 - 22:15:01

原始链接:http://yoursite.com/2018/09/15/2018-09-15-Pytorch-Cifar10-train/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

------ 本文结束------
坚持原创技术分享,您的支持将鼓励我继续创作!
0%