当前位置:   article > 正文

PyTorch学习日记(四)_data.view_as

data.view_as

今天学习卷积神经网络的构建

一、构建卷积神经网络处理mnist数据集

        1.1 获取数据

        分别构建训练集和测试集(验证集);用DataLoader来迭代取数据:

  1. import torch
  2. import torch.nn as nn
  3. import torch.optim as optim
  4. import torch.nn.functional as F
  5. import matplotlib.pyplot as plt
  6. from torchvision import datasets,transforms
  7. import numpy as np
  8. #定义超参数
  9. input_size = 28 #图像尺寸为28*28
  10. num_classes = 10 #标签的种类数
  11. num_epochs = 3 #训练的总循环周期
  12. batch_size = 64 #批处理的数量
  13. #训练集,这里基于datasets里的Mnist模块读取
  14. train_dataset = datasets.MNIST(root='./data',
  15. train=True,
  16. transform=transforms.ToTensor(),
  17. download=True)
  18. #测试集
  19. test_dataset = datasets.MNIST(root='./data',
  20. train=False,
  21. transform=transforms.ToTensor())
  22. #构建batch数据
  23. train_loader = torch.utils.data.DataLoader(dataset = train_dataset,
  24. batch_size = batch_size,
  25. shuffle = True)
  26. test_loader = torch.utils.data.DataLoader(dataset = test_dataset,
  27. batch_size = batch_size,
  28. shuffle = True)

        1.2 卷积网络模块构建

        一般卷积层,relu层,池化层可以写为一个套餐;注意卷积最后结果是特征图,需要把图转换为向量才能做分类或者回归任务: 

  1. class CNN(nn.Module):
  2. def __init__(self):
  3. super(CNN,self).__init__()
  4. self.conv1 = nn.Sequential( #输入为(1,28,28)
  5. nn.Conv2d(
  6. in_channels=1, #通道数,这里灰度图为1
  7. out_channels=16, #要得到几个特征图,即卷积核个数
  8. kernel_size=5, #卷积核大小
  9. stride=1, #步长
  10. padding=2, #如果希望卷积后大小和原来一样,需要设置padding=(kernel_size-1)/2 if stride=1
  11. ),
  12. nn.ReLU(),
  13. nn.MaxPool2d(kernel_size=2), #输出结果为(16,14,14)
  14. )
  15. self.conv2 = nn.Sequential( #输入为(16,14,14)
  16. nn.Conv2d(16,32,5,1,2),
  17. nn.ReLU(),
  18. nn.MaxPool2d(2), #输出为(32,7,7)
  19. )
  20. self.out = nn.Linear(32*7*7,10)
  21. def forward(self,x):
  22. x = self.conv1(x)
  23. x = self.conv2(x)
  24. x = x.view(x.size(0),-1) #flatten操作,结果为:(batch_size,32*7*7)
  25. print(x.size())
  26. out = self.out(x)
  27. return out

   

 1.3 训练网络模型

  1. #设置准确率函数作为评估标准
  2. def accuracy(predictions,labels):
  3. pred = torch.max(predictions.data,1)[1]
  4. rights = pred.eq(labels.data.view_as(pred)).sum()
  5. return rights, len(labels)
  6. #实例化
  7. net = CNN()
  8. #损失函数
  9. criterion = nn.CrossEntropyLoss()
  10. #优化器
  11. optimizer = optim.Adam(net.parameters(),lr=0.001)
  12. #开始训练循环
  13. for epoch in range(num_epochs):
  14. #当前epoch的结果保存下来
  15. train_rights = []
  16. for batch_idx, (data,target) in enumerate(train_loader): #对容器中的每一个批次进行循环
  17. net.train()
  18. output = net(data)
  19. loss = criterion(output,target)
  20. optimizer.zero_grad()
  21. loss.backward()
  22. optimizer.step()
  23. right = accuracy(output,target)
  24. train_rights.append(right)
  25. if batch_idx % 100 == 0:
  26. net.eval()
  27. val_rights = []
  28. for (data,target) in test_loader:
  29. output = net(data)
  30. right = accuracy(output,target)
  31. val_rights.append(right)
  32. #准确率计算
  33. train_r = (sum([tup[0] for tup in train_rights]),sum([tup[1] for tup in train_rights]))
  34. val_r = (sum([tup[0] for tup in val_rights]),sum([tup[1] for tup in val_rights]))
  35. print('当前epoch:{} [{}/{} ({:.0f}%)]\t损失:{:.6f}\t训练集准确率:{:.2f}%\t测试集准确率:{:.2f}%'.format(
  36. epoch, batch_idx * batch_size, len(train_loader.dataset),
  37. 100. * batch_idx / len(train_loader),
  38. loss.data,
  39. 100. * train_r[0].numpy() / train_r[1],
  40. 100. * val_r[0].numpy() / val_r[1],
  41. ))

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/372486?site
推荐阅读
相关标签
  

闽ICP备14008679号