本站消息

  本站每日ip已达10000,出租广告位,位置价格可谈,需要合作请联系站长


+关注
已关注

标签  

日期归档  

2018-12(32)

2019-01(27)

2019-02(8)

2019-03(7)

2019-04(1)

pytorch 用Lenet5实现MNIST手写数字识别,迭代100次,正确率99.32%

发布于2020-03-31 15:38     阅读(793)     评论(0)     点赞(25)     收藏(5)


1.训练模型

  1. import torch
  2. import torchvision
  3. from torchvision import datasets,transforms
  4. import matplotlib.pyplot as plt
  5. import numpy as np
  6. import cv2
  7. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  8. transform = transforms.Compose([
  9. transforms.ToTensor(), # 转为Tensor
  10. transforms.Normalize((0.5,), (0.5,)), # 归一化
  11. ])
  12. train_dataset = torchvision.datasets.MNIST(root='./mnist', train=True, transform=transform, download=True)
  13. test_dataset = torchvision.datasets.MNIST(root='./mnist', train=False, transform=transform, download=True)
  14. batch_size = 4
  15. trainloader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=False, num_workers=4)
  16. testloader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=4)
  17. import torch.nn as nn
  18. import torch.nn.functional as F
  19. class Net(nn.Module):
  20. def __init__(self):
  21. super(Net, self).__init__()
  22. self.conv1 = nn.Conv2d(1, 6, 5, padding=2)
  23. self.conv2 = nn.Conv2d(6, 16, 5)
  24. self.fc1 = nn.Linear(16*5*5, 120)
  25. self.fc2 = nn.Linear(120, 84)
  26. self.fc3 = nn.Linear(84, 10)
  27. def forward(self, x):
  28. x = F.max_pool2d(F.relu(self.conv1(x)), (2,2))
  29. x = F.max_pool2d(F.relu(self.conv2(x)), 2)
  30. x = x.view(x.size()[0], -1) #展开成一维的
  31. x = F.relu(self.fc1(x))
  32. x = F.relu(self.fc2(x))
  33. x = self.fc3(x)
  34. return x
  35. net = Net()
  36. net.to(device)
  37. print(net)
  38. from torch import optim
  39. criterion = nn.CrossEntropyLoss() # 交叉熵损失函数
  40. optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) # 优化器
  41. import time
  42. start_time = time.time()
  43. for epoch in range(100):
  44. running_loss = 0.0 #初始化loss
  45. for i, (inputs, labels) in enumerate(trainloader, 0):
  46. # 输入数据
  47. inputs = inputs.to(device)
  48. labels = labels.to(device)
  49. # 梯度清零
  50. optimizer.zero_grad()
  51. # forward + backward
  52. outputs = net(inputs)
  53. loss = criterion(outputs, labels)
  54. loss.backward()
  55. # 更新参数
  56. optimizer.step()
  57. # 打印log信息
  58. # loss 是一个scalar,需要使用loss.item()来获取数值,不能使用loss[0]
  59. running_loss += loss.item()
  60. if i % 2000 == 1999: # 每2000个batch打印一下训练状态
  61. print('[%d, %5d] loss: %.3f' % (epoch+1, i+1, running_loss / 2000))
  62. running_loss = 0.0
  63. stop_time = time.time()
  64. print('Finished Training 耗时: ', (stop_time - start_time), '秒')

2.保存模型

  1. PATH = './mnist_net_100.pth'
  2. torch.save(net.state_dict(), PATH)

3.读取并加载保存的模型

  1. pretrained_net = torch.load(PATH)
  2. net2 = Net()
  3. net2.load_state_dict(pretrained_net)

4.在测试集上进行测试

  1. #整个测试集上预测
  2. correct = 0
  3. total = 0
  4. with torch.no_grad():
  5. for (images,labels) in testloader:
  6. images = images.to(device)
  7. labels = labels.to(device)
  8. outputs = net(images)
  9. _, predicted = torch.max(outputs,1)
  10. total += labels.size(0)
  11. correct += (predicted == labels).sum()
  12. print('10000张测试集合中的准确率为:', (correct.cpu().numpy()/total * 100))
  13. print(correct)

5.抽取数据进行识别和显示

  1. classes = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
  2. #**测试图像的实际labels**
  3. dataiter = iter(testloader) #把测试数据放在迭代器iter
  4. images, labels = dataiter.next() # 一个batch返回4张图片,依次获取下一个数据
  5. images = images.to(device)
  6. labels = labels.to(device)
  7. print('实际的label: ', ' '.join( '%08s'%classes[labels[j]] for j in range(4)))
  8. print(images/2+0.5)
  9. img = np.empty((28,28*4), dtype=np.float32)
  10. img[:,0:28] = images[0].numpy()
  11. img[:,28:56] = images[1].numpy()
  12. img[:,56:84] = images[2].numpy()
  13. img[:,84:112] = images[3].numpy()
  14. img2 = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
  15. print(img2.shape)
  16. plt.imshow(img2)
  17. plt.show()

 



所属网站分类: 技术文章 > 博客

作者:熊猫烧香

链接: https://www.pythonheidong.com/blog/article/292562/

来源: python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

25 0
收藏该文
已收藏

评论内容:(最多支持255个字符)