zoukankan      html  css  js  c++  java
  • pytorch(十九):MNIST打印准确率和损失

    一、例子

     

     

     二、整体代码

    import torch
    from torch.nn import functional as F
    import torch.nn as nn
    import torchvision
    from torchvision import datasets,transforms
    import torch.optim as optim
    
    
    learning_rate = 1e-2
    batch_size = 64
    epochs = 10
    
    
    train_loader = torch.utils.data.DataLoader(torchvision.datasets.MNIST('datasets/mnist_data',
                    train=True,
                    download=True,
                    transform=torchvision.transforms.Compose([
                    torchvision.transforms.ToTensor(),                       # 数据类型转化
                    torchvision.transforms.Normalize((0.1307, ), (0.3081, )) # 数据归一化处理
        ])), batch_size=batch_size,shuffle=True)
    
    test_loader = torch.utils.data.DataLoader(torchvision.datasets.MNIST('datasets/mnist_data/',
                    train=False,
                    download=True,
                    transform=torchvision.transforms.Compose([
                    torchvision.transforms.ToTensor(),
                    torchvision.transforms.Normalize((0.1307, ), (0.3081, ))
        ])),batch_size=batch_size,shuffle=False)
    
    class MLP(nn.Module):
        def __init__(self):
            super(MLP,self).__init__()
            self.model = nn.Sequential(
                nn.Linear(784,200),
                nn.LeakyReLU(inplace = True),
                nn.Linear(200,200),
                nn.LeakyReLU(inplace = True),
                nn.Linear(200,10),
                nn.LeakyReLU(inplace = True)
            )
            
        def forward(self,x):
            x = self.model(x)
            
            return x
    
    device = torch.device('cuda:0')
    net = MLP().to(device)
    optimizer = optim.SGD(net.parameters(),lr = learning_rate)
    criteon = nn.CrossEntropyLoss().to(device)
    
    
    for epoch in range(epochs):
        for batch_idx,(data,target) in enumerate(train_loader):
            data = data.view(-1,28*28)
            data,target = data.to(device),target.to(device)
            
            logits = net(data)
            loss = criteon(logits,target)
            
            optimizer.zero_grad()
            loss.backward()
            
            optimizer.step()
            
            if batch_idx % 100 == 0:
                print('Train Epoch: {} [{}/{} ({:.0f}%)]	Loss: {:.6f}'.format(
                    epoch, batch_idx * len(data), len(train_loader.dataset),
                           100. * batch_idx / len(train_loader), loss.item()))
                
        test_loss = 0
        correct = 0
        for data, target in test_loader:
            data = data.view(-1, 28 * 28)
            data, target = data.to(device), target.cuda()
            logits = net(data)
            test_loss += criteon(logits, target).item()
    
            pred = logits.data.max(1)[1]
            correct += pred.eq(target.data).sum()
    
        test_loss /= len(test_loader.dataset)
        print('
    Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)
    '.format(
            test_loss, correct, len(test_loader.dataset),
            100. * correct / len(test_loader.dataset)))
  • 相关阅读:
    Android OCR 之 tesseract
    抛砖引玉 之 谁动了我的流量(0权限上传数据)
    退伍一年了
    android 通过 Hessian 与 j2ee 服务端交互
    Arduino 入手
    抛砖引玉 之 谁动了我的隐私(android用户隐私窥探)
    如何关注那些有价值的微博
    关于培训和外包20111027
    ASP.NET实现Cookie功能的三个基本操作(写入,读取,删除)
    提高你开发效率的十五个Visual Studio 2010使用技巧
  • 原文地址:https://www.cnblogs.com/zhangxianrong/p/14026609.html
Copyright © 2011-2022 走看看