Classification tasks for introductory learning of Pytorch code (4): training and testing network

1. Training network

1.1 Code

for epoch in range(2):
    
    running_loss = 0.0
    
    for i,data in enumerate(trainloader,0):
        inputs,labels = data
        optimizer.zero_grad()
        
        outputs = net(inputs)
        loss = criterion(outputs,labels)
        loss.backward()
        optimizer.step()
        
        running_loss += loss.item()
        
        if i % 2000 == 1999:
            print('[%d,%5d] loss:%.3f' % (epoch + 1,i+1,running_loss/2000))
            running_loss = 0.0
 
print("Finish")

Note: enumerater in python means that receives an iterable object as a parameter (you can also The start parameter is used to indicate the starting index, that is, the following 0), and a tuple is returned. The first bit of the tuple is the iteration number (from a>0), the second digit is an item of the iterable object.

1.2 Purpose of training network

       Through a loop, take the data from the training data set according to the batch, feed the data to the network, and get the prediction results of the network, use to calculate the loss, and then reverse the loss Propagate the gradients of all parameters, and finally use  to update the parameters.  loss_function optimizer

        The network updates based on the input data, labels the images and lets the network calculate the loss function, then updates the network parameters and generates a model.

1.3 Save training parameters 

PATH='./cifar_net.pth'
torch.save(net.state_dict(),PATH)

1.4 Check the correct output

dataiter = iter(testloader)
images,labels = dataiter.next()
imshow(torchvision.utils.make_grid(images))
print('GroundTruth:',' '.join('%5s'% classes[labels[j]] for j in range(4)))

2. Test network

2.1 Check the prediction effect

# 实例化网络
net = Net()
PATH='./cifar_net.pth'
net.load_state_dict(torch.load(PATH))
outputs = net(images)
_,predicted = torch.max(outputs,1)
print('Predicted:',' '.join('%5s'% classes[predicted[j]] for j in range(5)))

2.2 Accuracy

        Unlike the training network, the test network does not need to calculate the gradient. The code of the test network is usually completed under torch.no_grad()

        The accuracy rate can be used to observe the prediction result performance of the entire training set:

correct = 0
total = 0  # 整个数据集的大小
with torch.no_grad():
    for data in testloader:
        images,labels = data
        outputs = net(images)
        _,predicted = torch.max(outputs,1)
        
        total += labels.size(0)
        # 两个维度的向量逐行对比,相同的即正确的行记为1,不同的即不准确的行记为0,利用sum()求各元素的总和
        correct += (predicted == labels).sum().item()
 
correctGailv = 100*(correct / total)
print(correctGailv)

Note: Perform max operation on the output vector to get the class with the maximum value.

        (Because the training times are too few, the accuracy is low.)

        Reference:006 The first classification task is completed_bilibili_bilibili

Guess you like

Origin blog.csdn.net/m0_53096519/article/details/134069482