import torch
import torchvision.datasets
from torchvision import transforms
from torch.utils.data import DataLoader
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
#追踪日志
writer = SummaryWriter(log_dir='../LEDR')
#准备数据集
trans = transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.1307,),(0.3801,))])
train_set = torchvision.datasets.MNIST(root='E:\learn_pytorch\LE',train=True,transform=trans,download=True)
test_set = torchvision.datasets.MNIST(root='E:\learn_pytorch\LE',train=False,transform=trans,download=True)
#加载数据集
train_data = DataLoader(dataset=train_set,batch_size=64,shuffle=True)
test_data = DataLoader(dataset=test_set,batch_size=64,shuffle=False)
#模型构建
class conv_model_1(torch.nn.Module):
def __init__(self):
super(conv_model_1, self).__init__()
self.conv_1 = torch.nn.Conv2d(1,10,(5,5))
self.conv_2 = torch.nn.Conv2d(10,20,(5,5))
self.conv_3 = torch.nn.Conv2d(20,30,(3,3))
self.pooling = torch.nn.MaxPool2d(2)
self.fc1 = torch.nn.Linear(30,20)
self.fc2 = torch.nn.Linear(20,10)
def forward(self,x):
x = F.relu(self.conv_1(x))
x = self.pooling(x)
x = F.relu(self.conv_2(x))
x = self.pooling(x)
x = F.relu(self.conv_3(x))
x = self.pooling(x)
x = x.view(-1,30)
x = self.fc1(x)
x = self.fc2(x)
return x
#实例化模型
huihui = conv_model_1()
#定义损失函数和优化函数
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(params=huihui.parameters(),lr=0.01,momentum=0.5)
#开始训练
def train(epoch):
run_loss = 0.0
for batch_id , data in enumerate(train_data,0):
inputs , targets = data
outputs = huihui(inputs)
loss = criterion(outputs, targets)
#归零,反馈,更新
optimizer.zero_grad()
loss.backward()
optimizer.step()
run_loss += loss.item()
if batch_id % 300 == 299:
print("[%d,%d] loss:%.3f" %(epoch+1,batch_id+1,run_loss/300))
run_loss = 0.0
def test():
total = 0
correct = 0
with torch.no_grad():
for data in test_data:
inputs , labels = data
outputs = huihui(inputs)
_,predict = torch.max(outputs,dim=1)
total += labels.size(0)
correct += (predict==labels).sum().item()
writer.add_scalar("The Accuracy",correct/total,epoch)
print('[Accuracy] %d %%' % (100*correct/total))
if __name__ == '__main__':
for epoch in range(10):
train(epoch)
test()
writer.close()
D:\Anaconda3\envs\pytorch\python.exe E:/learn_pytorch/LE/conv_base_homework.py
[1,300] loss:2.101
[1,600] loss:0.555
[1,900] loss:0.283
[Accuracy] 92 %
[2,300] loss:0.196
[2,600] loss:0.161
[2,900] loss:0.147
[Accuracy] 95 %
[3,300] loss:0.118
[3,600] loss:0.115
[3,900] loss:0.105
[Accuracy] 97 %
[4,300] loss:0.092
[4,600] loss:0.090
[4,900] loss:0.084
[Accuracy] 97 %
[5,300] loss:0.073
[5,600] loss:0.075
[5,900] loss:0.075
[Accuracy] 97 %
[6,300] loss:0.068
[6,600] loss:0.066
[6,900] loss:0.057
[Accuracy] 98 %
[7,300] loss:0.060
[7,600] loss:0.057
[7,900] loss:0.056
[Accuracy] 98 %
[8,300] loss:0.053
[8,600] loss:0.053
[8,900] loss:0.047
[Accuracy] 98 %
[9,300] loss:0.047
[9,600] loss:0.046
[9,900] loss:0.048
[Accuracy] 98 %
[10,300] loss:0.043
[10,600] loss:0.042
[10,900] loss:0.047
[Accuracy] 98 %Process finished with exit code 0