如何使用 matplotlib 在 pytorch 上显示损失和准确性的图表

Ka_*_*Ka_ 7 python matplotlib conv-neural-network pytorch

我是 pytorch 的新手,我想知道如何显示损失和准确性的图表,以及我应该如何准确存储这些值,知道我正在使用 CIFAR10 应用 cnn 模型进行图像分类。

这是我当前的实现:

    def train(num_epochs,optimizer,criterion,model):
        for epoch in range(num_epochs):
            for i, (images, labels) in enumerate(trainloader):
                # origin shape: [4, 3, 32, 32] = 4, 3, 1024
                # input_layer: 3 input channels, 6 output channels, 5 kernel size
                images = images.to(device)
                labels = labels.to(device)
    
                # Forward pass
                outputs = model(images)
                loss = criterion(outputs, labels)
    
                # Backward and optimize
                optimizer.zero_grad()
                loss.backward()
                optimizer.step()
    
                if (i+1) % 2000 == 0:
                    print (f'Epoch [{epoch+1}/{num_epochs}], Step [{i+1}/{n_total_steps}], Loss: {loss.item():.4f}')
                
        
        PATH = './cnn.pth'
        torch.save(model.state_dict(), PATH)
    
    
    def test ():
        with torch.no_grad():
            n_correct = 0
            n_samples = 0
            n_class_correct = [0 for i in range(10)]
            n_class_samples = [0 for i in range(10)]
        
            for images, labels in testloader:
                images = images.to(device)
                labels = labels.to(device)
                outputs = model(images)
                # max returns (value ,index)
                _, predicted = torch.max(outputs, 1)
                n_samples += labels.size(0)
                n_correct += (predicted == labels).sum().item()
            
                for i in range(batch_size):
                    label = labels[i]
                    pred = predicted[i]
                
                    if (label == pred):
                        n_class_correct[label] += 1
                    n_class_samples[label] += 1
    
            acc = 100.0 * n_correct / n_samples
            print(f'Accuracy of the network: {acc} %')
        
    
            for i in range(10):
                acc = 100.0 * n_class_correct[i] / n_class_samples[i]
                print(f'Accuracy of {classes[i]}: {acc} %')
            
            
            test_score = np.mean([100 * n_class_correct[i] / n_class_samples[i] for i in range(10)])
            print("the score test is : {0:.3f}%".format(test_score))
            return acc
Run Code Online (Sandbox Code Playgroud)

小智 10

您需要做的是:对所有批次的损失进行平均,然后在每个时期后将其附加到一个变量,然后绘制它。实施将是这样的:

import matplotlib.pyplot as plt

def my_plot(epochs, loss):
    plt.plot(epochs, loss)
    
def train(num_epochs,optimizer,criterion,model):
    loss_vals=  []
    for epoch in range(num_epochs):
        epoch_loss= []
        for i, (images, labels) in enumerate(trainloader):
            # rest of the code
            loss.backward()
            epoch_loss.append(loss.item())
            # rest of the code
        # rest of the code
        loss_vals.append(sum(epoch_loss)/len(epoch_loss))
        # rest of the code
    
    # plotting
    my_plot(np.linspace(1, num_epochs, num_epochs).astype(int), loss_vals)

my_plot([1, 2, 3, 4, 5], [100, 90, 60, 30, 10])
Run Code Online (Sandbox Code Playgroud)

您可以进行类似的计算以确保准确性。