【问题标题】:How to display graphs of loss and accuracy on pytorch using matplotlib如何使用 matplotlib 在 pytorch 上显示损失和准确度图
【发布时间】:2020-07-26 21:52:47
【问题描述】:

我是 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

【问题讨论】:

    标签: python matplotlib pytorch conv-neural-network


    【解决方案1】:

    您需要做的是:平均所有批次的损失,然后在每个 epoch 之后将其附加到一个变量中,然后绘制它。实现是这样的:

    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])
    

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

    【讨论】:

    • 当前代码确实平均。平均理想情况下,您需要执行 epoch_loss.append(loss.item() * images.shape[0])。在 epoch 结束时,sum(epoch_loss) / len(training of dataset)
    猜你喜欢
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 2019-04-30
    • 2017-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    相关资源
    最近更新 更多