MNIST Pytorch官方代码解读

前言

最近要学习dqn,项目组用pytorch作为深度学习框架,以此记录pytorch的学习笔记
因为是速成的,一周看的python,半周numpy,到现在一周半的pytorch,如果有错误请大家指出
Mnist的pytorch官方代码可以说是非常好的一个案例,这里以我现在的理解能力对其进行了详细注释,后面再给出可用的简化代码,官方代码保证了跨平台的可用性,个人的话许多写法可以去掉。

全部代码

from __future__ import print_function
#这句话是针对python2引入python3的print函数,可以不写
import argparse
#一个参数管理包
import torch
#pytorch模块包,不用多解释
import torch.nn as nn
#nn主要包含了各种网络,例如Linear,Conv2D,Droupout等,详见 https://pytorch.org/docs/stable/nn.html
import torch.nn.functional as F
#functional主要包含了各类激活函数,详见 https://pytorch.org/docs/stable/nn.functional.html
#functional包含了nn的部分网络层功能,但需要额外指定w,b等
import torch.optim as optim
#各类优化器的功能包,详见 https://pytorch.org/docs/stable/optim.html
#优化器的选择一定要注意学习率问题,越快的优化器要用更小的学习率lr才能不发散
from torchvision import datasets, transforms
#datasets包含了各类开源的数据集,如果用自己的数据集可以不调用
#transforms是批量变换成torch类型的功能包,从各种其他类型如numpy转成tensor类型都要用到。
from torch.optim.lr_scheduler import StepLR
#这是学习率衰减函数,为了在后期更好地下降到梯度为0的点,但不加影响也不大,后期在一定范围内震荡


class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()#使用父类的所有__init__功能
        self.conv1 = nn.Conv2d(1, 32, 3, 1)
        #28*28*1->26*26*32
        self.conv2 = nn.Conv2d(32, 64, 3, 1)
        #26*26*32->24*24*64
        #注意这里的卷积核大小是64*32*3*3,而不是2*3*3,可见卷积的参数量极其庞大
        self.dropout1 = nn.Dropout(0.25)
        self.dropout2 = nn.Dropout(0.5)
        self.fc1 = nn.Linear(9216, 128)
        #9216 = 12*12*64128作为全连接的过渡层
        self.fc2 = nn.Linear(128, 10)

    def forward(self, x):
        x = self.conv1(x)
        x = F.relu(x)
        x = self.conv2(x)
        x = F.relu(x)
        x = F.max_pool2d(x, 2)
        #最大池化,相比平均池化特征更明显,24*24*64->12*12*64
        x = self.dropout1(x)
        x = torch.flatten(x, 1)
        x = self.fc1(x)
        x = F.relu(x)
        x = self.dropout2(x)
        x = self.fc2(x)
        output = F.log_softmax(x, dim=1)
        #log_softmax激活函数一定要搭配 nll_loss() 损失函数处理分类问题
        #如果直接输出x,则可以用 CrossEntropyLoss() 损失函数处理分类问题,见莫凡教程
        #两者区别不大 CrossEntropyLoss() 在内部求了 log_softmax(x,dim =1)return output


def train(args, model, device, train_loader, optimizer, epoch):
    model.train()
    #注意和test时的 model.eval()区分,这里启用 BatchNormalization 和 Dropout
    for batch_idx, (data, target) in enumerate(train_loader):
    # enumerate()将数据组合为可索引的序列,并返回下标
        data, target = data.to(device), target.to(device)
        # 将输入数据,期望值传入到cuda中,如果用gpu必须写,不然和net无法连通
        optimizer.zero_grad()
        #梯度归零
        output = model(data)
        #计算输出值,整个batch的输出值,返回一个tensor
        loss = F.nll_loss(output, target)
        #计算loss,具体哪种loss对应哪种问题自行查阅
        loss.backward()
        #误差的反向计算,更新梯度
        optimizer.step()
        #由算出来的梯度进行优化
        if batch_idx % args.log_interval == 0:
        #训练时的输出
            print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                100. * batch_idx / len(train_loader), loss.item()))
            # .item()取torch变量的数据值
            if args.dry_run:
                break


def test(model, device, test_loader):
    model.eval()
    #计算测试样本的效果时,这里不启用 BatchNormalization 和 Dropout
    test_loss = 0
    correct = 0
    with torch.no_grad():
    #确保不进行梯度计算
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)
            output = model(data)
            test_loss += F.nll_loss(output, target, reduction='sum').item()  # sum up batch loss
            pred = output.argmax(dim=1, keepdim=True)  # get the index of the max log-probability
            correct += pred.eq(target.view_as(pred)).sum().item()
            # a.view_as(b)与reshape类似,将a变成b的维度格式。 a.eq(b)计算数值相等,返回bool类型列表。

    test_loss /= len(test_loader.dataset)

    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
        test_loss, correct, len(test_loader.dataset),
        100. * correct / len(test_loader.dataset)))


def main():
    # Training settings
    parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
    parser.add_argument('--batch-size', type=int, default=64, metavar='N',
                        help='input batch size for training (default: 64)')
    parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
                        help='input batch size for testing (default: 1000)')
    parser.add_argument('--epochs', type=int, default=14, metavar='N',
                        help='number of epochs to train (default: 14)')
    parser.add_argument('--lr', type=float, default=1.0, metavar='LR',
                        help='learning rate (default: 1.0)')
    parser.add_argument('--gamma', type=float, default=0.7, metavar='M',
                        help='Learning rate step gamma (default: 0.7)')
    parser.add_argument('--no-cuda', action='store_true', default=False,
                        help='disables CUDA training')
    parser.add_argument('--dry-run', action='store_true', default=False,
                        help='quickly check a single pass')
    parser.add_argument('--seed', type=int, default=1, metavar='S',
                        help='random seed (default: 1)')
    parser.add_argument('--log-interval', type=int, default=10, metavar='N',
                        help='how many batches to wait before logging training status')
    parser.add_argument('--save-model', action='store_true', default=False,
                        help='For Saving the current Model')
    args = parser.parse_args()
    use_cuda = not args.no_cuda and torch.cuda.is_available()

    torch.manual_seed(args.seed)

    device = torch.device("cuda" if use_cuda else "cpu")
	#是否使用GPU计算
	
    train_kwargs = {'batch_size': args.batch_size}
    test_kwargs = {'batch_size': args.test_batch_size}
    if use_cuda:
        cuda_kwargs = {'num_workers': 4,
        			   #同时使用的线程数,>2个加载数据集速度会变快
                       'pin_memory': True,
                       #如果使用gpu计算,则要先锁内存
                       'shuffle': True}
                       #是否打乱顺序
        train_kwargs.update(cuda_kwargs)
        #python字典的update方法,将两个字典合并
        test_kwargs.update(cuda_kwargs)
    #通过创建字典作为DataLoader的形参

    transform=transforms.Compose([
        transforms.ToTensor(),
        #将数据集numpy等类型转成tensor类型,并且初始化为-11之间的值
        transforms.Normalize((0.1307,), (0.3081,))
        #正则化,可以不要
        ])
    dataset1 = datasets.MNIST('../data', train=True, download=True,
                       transform=transform)
                       #加载训练数据集,并做变换
    dataset2 = datasets.MNIST('../data', train=False,
                       transform=transform)
                       #加载测试集
    train_loader = torch.utils.data.DataLoader(dataset1,**train_kwargs)
    #用dataloader生成用于批训练的数据集
    test_loader = torch.utils.data.DataLoader(dataset2, **test_kwargs)

    model = Net().to(device)
    #生成net对象并传送至gpu
    optimizer = optim.Adadelta(model.parameters(), lr=args.lr)
    #使用Adadelta优化函数,注意各种优化函数的学习率选择,大多数时候默认值就可以

    scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma)
    #学习率衰减
    for epoch in range(1, args.epochs + 1):
        train(args, model, device, train_loader, optimizer, epoch)
        test(model, device, test_loader)
        scheduler.step()

    if args.save_model:
        torch.save(model.state_dict(), "mnist_cnn.pt")
        #这里是保存的w,b的参数值,没有保存整个模型

if __name__ == '__main__':
    main()

简化了一点点的代码,换了Cross_entropy损失函数

import torch
import torch.nn as nn
import torch.nn.functional as F 
import torch.optim as optim
from torchvision import datasets,transforms
import torch.utils.data as Data 

class Net(nn.Module):
    def __init__(self):
        super(Net,self).__init__()
        self.conv1 = nn.Conv2d(1,32,3,1,1)
        self.conv2 = nn.Conv2d(32,64,3,1,1)
        self.dropout1 = nn.Dropout(0.25)
        self.dropout2 = nn.Dropout(0.25)
        self.fc1 = nn.Linear(14*14*64,128)
        self.fc2 = nn.Linear(128,10)

    def forward(self,x):
        x = self.conv1(x)
        x = F.relu(x)
        x = self.conv2(x)
        x = F.relu(x)
        x = F.max_pool2d(x,2)
        x = self.dropout1(x)

        x = torch.flatten(x,1)
        x = self.fc1(x)
        x = F.relu(x)
        x = self.dropout2(x)
        x = self.fc2(x)
        #直接输出的话用F.cross_entropy()
        output = F.log_softmax(x,dim=1)
        #套用log_softmax()输出后用nll_loss()
        return output,x

def train(model,device,train_loader,optimizer,epochs):
    model.train()
    for batch_idx,(data,target) in enumerate(train_loader):
        data,target = data.to(device),target.to(device)
        optimizer.zero_grad()
        output,x= model(data)
        loss = F.cross_entropy(x,target)
        #loss = F.nll_loss(output,target)
        loss.backward()
        optimizer.step()

        if batch_idx%10 ==0:
            print('train epochs:{} [{}/{} ({:.0f}%)]\t Loss: {:.6f}'.format(
                epochs,batch_idx*len(data),len(train_loader.dataset),
                100.*batch_idx/len(train_loader),loss.item()
            ))

def test(model,device,test_loader):
    model.eval()
    test_loss = 0
    correct = 0
    with torch.no_grad():
        for data,target in test_loader:
            data,target = data.to(device),target.to(device)
            output,x= model(data)
            test_loss += F.cross_entropy(x,target,reduction='sum').item()
            #test_loss += F.nll_loss(output,target,reduction='sum').item()
            pred = output.argmax(dim = 1,keepdim = True)
            correct += pred.eq(target.view_as(pred)).sum().item()
    test_loss /= len(test_loader.dataset)

    print('\nTest set: Average loss: {:.6f}, Accuracy: {}/{} ({:.3f}%)\n'.format(
        test_loss,correct,len(test_loader.dataset),
        100.*correct/len(test_loader.dataset)))

def main():
    device = torch.device('cuda')

    transform = transforms.ToTensor()

    datasets1 = datasets.MNIST('../data',train = True,download=True,transform=transform)
    datasets2 = datasets.MNIST('../data',train = False,transform=transform)

    train_kws = {'batch_size':64,'num_workers':4,'pin_memory':True,'shuffle':True}
    test_kws = {'batch_size':1000,'num_workers':2,'pin_memory':True,'shuffle':True}

    train_loader = Data.DataLoader(datasets1,**train_kws)
    test_loader = Data.DataLoader(datasets2,**test_kws)

    model = Net().to(device)
    optimizer = optim.Adam(model.parameters(),lr = 0.001)
    for epoch in range(10):
        train(model,device,train_loader,optimizer,epoch)
        test(model,device,test_loader)

    torch.save(model,'net1.pt')

if __name__ == '__main__':
    main()

你可能感兴趣的:(pytorch,pytorch,神经网络,深度学习)