用PyTorch完成手写数字识别
输出结果:
Epoch: [2/3] Iteration: [850/938] loss: 0.023803
Epoch: [2/3] Iteration: [900/938] loss: 0.021752
第2个epoch的识别准确率为:99.4000%
Epoch: [3/3] Iteration: [50/938] loss: 0.013843
Epoch: [3/3] Iteration: [100/938] loss: 0.014237
Epoch: [3/3] Iteration: [150/938] loss: 0.016309
Loss 可视化:
代码:
import torch
import torch
.nn
as nn
import torchvision
as tv
from torch
.utils
import data
from torchvision
import transforms
as T
import os
import numpy
as np
from PIL
import Image
import matplotlib
.pyplot
as plt
import tensorboardX
from utils
import show_confMat
, validate
device
= torch
.device
("cuda" if torch
.cuda
.is_available
() else "cpu")
transform
= T
.Compose
([T
.Resize
(224),
T
.ToTensor
()])
data_train
= tv
.datasets
.MNIST
(
root
='./data/mnist/',
train
=True,
download
=True,
transform
=transform
)
trainloader
= data
.DataLoader
(
data_train
,
batch_size
=64,
shuffle
=True,
)
data_test
= tv
.datasets
.MNIST
(
root
='./data/mnist/',
train
=False,
download
=True,
transform
=transform
)
testloader
= data
.DataLoader
(
data_test
,
batch_size
=64,
shuffle
=False,
)
net
= tv
.models
.resnet18
(True)
net
.conv1
= nn
.Conv2d
(1, 64, kernel_size
=(7, 7), stride
=(2, 2), padding
=(3, 3), bias
=False)
net
.fc
=nn
.Linear
(512, 10)
net
.to
(device
)
import torch
.optim
as optim
criterion
= nn
.CrossEntropyLoss
()
optimizer
= optim
.SGD
(net
.parameters
(), lr
=0.001, momentum
=0.9)
from tensorboardX
import SummaryWriter
writer
= SummaryWriter
(logdir
="./log/")
for epoch
in range(3):
sum_loss
= 0.0
epoch_loss
= 0.0
for i
, data
in enumerate(trainloader
):
img
, labeles
= data
img
, labeles
= img
.to
(device
), labeles
.to
(device
)
optimizer
.zero_grad
()
outputs
= net
(img
)
loss
= criterion
(outputs
, labeles
)
loss
.backward
()
optimizer
.step
()
sum_loss
+= loss
.item
()
epoch_loss
+= loss
.item
()
if (i
+1) % 50 == 0:
print('Epoch: [{}/{}] Iteration: [{}/{}] loss: {:6f}'.\
format(epoch
+1, 3, i
+1, len(trainloader
), sum_loss
/ 50))
writer
.add_scalars
('Loss', {'train_loss': sum_loss
/ 50}, epoch
*len(trainloader
)+i
+1)
sum_loss
= 0.0
with torch
.no_grad
():
correct
= 0
total
= 0
for data
in testloader
:
images
, labels
= data
images
, labels
= images
.to
(device
), labels
.to
(device
)
outputs
= net
(images
)
_
, predicted
= torch
.max(outputs
.data
, 1)
total
+= labels
.size
(0)
correct
+= (predicted
== labels
).sum().item
()
print('第{}个epoch的识别准确率为:{:.4%}'.format(epoch
+1, 100.0 * correct
/ total
))
torch
.save
(net
.state_dict
(), './net_{}.pth'.format(epoch
+1))
转载请注明原文地址: https://yun.8miu.com/read-135008.html