当前位置:   article > 正文

【PyTorch】GPU实现cnn手写数字识别_pytorch gpu手写数字

pytorch gpu手写数字

核心思想:

将数据与整个网络都集成到GPU进行运算。

代码

  1. #gpu方式的mnist手写数字识别
  2. import torch
  3. import torch.nn as nn
  4. import torch.optim as optim
  5. import torch.nn.functional as F
  6. from torch.autograd import Variable
  7. import torch.utils.data as Data
  8. import torchvision
  9. import matplotlib.pyplot as plt
  10. import numpy as np
  11. EPOCH = 1
  12. BATCH_SIZE = 50
  13. LR = 0.001
  14. DOWNLOAD_MNIST = False
  15. train_data = torchvision.datasets.MNIST(
  16. root='./mnist',
  17. train=True,
  18. transform=torchvision.transforms.ToTensor(),
  19. download=DOWNLOAD_MNIST
  20. )
  21. train_loader = Data.DataLoader(
  22. dataset=train_data,
  23. batch_size=BATCH_SIZE,
  24. shuffle=True,
  25. num_workers=2
  26. )
  27. test_data = torchvision.datasets.MNIST(
  28. root='./mnist',
  29. train=False
  30. )
  31. #change in here
  32. test_x = Variable(torch.unsqueeze(test_data.test_data, dim=1)).type(torch.FloatTensor)[:2000].cuda()/255. # Tensor on GPU
  33. test_y = test_data.test_labels[:2000].cuda()
  34. class CNN(nn.Module):
  35. def __init__(self):
  36. super(CNN,self).__init__()
  37. self.conv1 = nn.Sequential(
  38. nn.Conv2d(1,16,5,1,2),
  39. nn.ReLU(),
  40. nn.MaxPool2d(kernel_size=2)
  41. )
  42. self.conv2 = nn.Sequential(
  43. nn.Conv2d(16,32,5,1,2),
  44. nn.ReLU(),
  45. nn.MaxPool2d(kernel_size=2)
  46. )
  47. self.out = nn.Linear(32 * 7 * 7,10) #10分类的问题
  48. def forward(self,x):
  49. x = self.conv1(x)
  50. x = self.conv2(x)
  51. x = x.view(x.size(0),-1)
  52. x = self.out(x)
  53. return x
  54. def main():
  55. cnn = CNN()
  56. cnn.cuda()
  57. optimizer = optim.Adam(cnn.parameters(),lr=LR)
  58. loss_func = nn.CrossEntropyLoss()
  59. for epoch in range(EPOCH):
  60. for step,(x,y) in enumerate(train_loader):
  61. b_x = Variable(x).cuda()
  62. b_y = Variable(y).cuda()
  63. output = cnn(b_x)
  64. loss = loss_func(output,b_y)
  65. optimizer.zero_grad()
  66. loss.backward()
  67. optimizer.step()
  68. if step % 50 == 0:
  69. test_output = cnn(test_x)
  70. # !!!!!!!! Change in here !!!!!!!!! #
  71. pred_y = torch.max(test_output, 1)[1].cuda().data.squeeze() # move the computation in GPU
  72. accuracy = torch.sum(pred_y == test_y).type(torch.FloatTensor) / test_y.size(0)
  73. print('Epoch: ', epoch, '| train loss: %.4f' % loss.item(), '| test accuracy: %.2f' % accuracy)
  74. if __name__ == '__main__':
  75. main()

结果:

  1. Epoch: 0 | train loss: 2.3063 | test accuracy: 0.10
  2. Epoch: 0 | train loss: 0.5096 | test accuracy: 0.83
  3. Epoch: 0 | train loss: 0.3086 | test accuracy: 0.91
  4. Epoch: 0 | train loss: 0.5883 | test accuracy: 0.91
  5. Epoch: 0 | train loss: 0.1175 | test accuracy: 0.93
  6. Epoch: 0 | train loss: 0.1339 | test accuracy: 0.94
  7. Epoch: 0 | train loss: 0.1315 | test accuracy: 0.95
  8. Epoch: 0 | train loss: 0.1148 | test accuracy: 0.96
  9. Epoch: 0 | train loss: 0.0298 | test accuracy: 0.96
  10. Epoch: 0 | train loss: 0.3159 | test accuracy: 0.97
  11. Epoch: 0 | train loss: 0.0756 | test accuracy: 0.97
  12. Epoch: 0 | train loss: 0.2151 | test accuracy: 0.97
  13. Epoch: 0 | train loss: 0.1290 | test accuracy: 0.96
  14. Epoch: 0 | train loss: 0.0385 | test accuracy: 0.97
  15. Epoch: 0 | train loss: 0.0358 | test accuracy: 0.97
  16. Epoch: 0 | train loss: 0.0849 | test accuracy: 0.97
  17. Epoch: 0 | train loss: 0.0173 | test accuracy: 0.97
  18. Epoch: 0 | train loss: 0.0424 | test accuracy: 0.98
  19. Epoch: 0 | train loss: 0.1845 | test accuracy: 0.97
  20. Epoch: 0 | train loss: 0.1270 | test accuracy: 0.97
  21. Epoch: 0 | train loss: 0.0263 | test accuracy: 0.98
  22. Epoch: 0 | train loss: 0.0845 | test accuracy: 0.98
  23. Epoch: 0 | train loss: 0.0639 | test accuracy: 0.98
  24. Epoch: 0 | train loss: 0.0223 | test accuracy: 0.98

 

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

闽ICP备14008679号