0


神经网络做MNIST手写数字识别代码

1.MNIST数据集

MNIST数据集是由0 到9 的手写数字图像构成的。训练图像有6 万张,测试图像有1 万张每一张图片都有对应的标签数字。因此这个测试集就可以作为验证集使用。

MNIST的图像,每张图片是包含28 像素× 28 像素的灰度图像(1 通道),各个像素的取值在0 到255 之间。每张图片都由一个28 ×28 的矩阵表示,每张图片都由一个784 维的向量表示(28*28=784)。
在这里插入图片描述

详细介绍参考:http://yann.lecun.com/exdb/mnist/

2.用神经网络做MNIST手写数字识别

模型结构:
在这里插入图片描述
模型如图所示,输入二维张量展开成一维。再经过若干次组合的,Linear层和激活函数层,最后返回。
在模型使用时,后面接到交叉熵损失函数上。所以模型的最后一层不做激活。因为本身交叉熵损失函数带有激活功能。
在这里插入图片描述

3.代码实现(python+pytorch)

分四个步骤:
第一步:数据集准备和加载;第二步:设计模型;第三步:构建损失函数和优化器;第四步:模型的训练和验证

因pytorc中封装了很多模块。所以我们在实现时,更多的是了解各个模块的功能,以便组合使用。

在这里插入图片描述

  1. import torch
  2. from torchvision import transforms
  3. from torchvision import datasets
  4. from torch.utils.data import DataLoader
  5. import torch.optim as optim
  6. import torch.nn.functional as F
  7. import matplotlib.pyplot as plt
  8. batch_size =64
  9. transform = transforms.Compose([
  10. transforms.ToTensor(),
  11. transforms.Normalize((0.1307),(0.3081))#两个参数,平均值和标准差])
  12. train_dataset = datasets.MNIST(root="../dataset/mnist/",
  13. train= True,
  14. download= True,
  15. transform= transform
  16. )
  17. train_loader = DataLoader(train_dataset,
  18. shuffle = True,
  19. batch_size = batch_size)
  20. test_dataset = datasets.MNIST(root="../dataset/mnist/",
  21. train=False,
  22. download=True,
  23. transform=transform
  24. )
  25. test_loder = DataLoader(test_dataset,
  26. shuffle = True,
  27. batch_size = batch_size)
  28. class Net(torch.nn.Module):
  29. def __init__(self):
  30. super(Net,self).__init__()
  31. self.linear1 = torch.nn.Linear(784,512)
  32. self.linear2 = torch.nn.Linear(512,256)
  33. self.linear3 = torch.nn.Linear(256,128)
  34. self.linear4 = torch.nn.Linear(128,64)
  35. self.linear5 = torch.nn.Linear(64,10)
  36. def forward(self,x):
  37. x = x.view(-1,784)# 改变张量形状。把输入展开成若干行,784
  38. x = F.leaky_relu(self.linear1(x))
  39. x = F.leaky_relu(self.linear2(x))
  40. x = F.leaky_relu(self.linear3(x))
  41. x = F.leaky_relu(self.linear4(x))return self.linear5(x)#最后一层不做激活,因为下一步输入到交叉损失函数中,交叉熵包含了激活层
  42. model = Net()
  43. criterion = torch.nn.CrossEntropyLoss()
  44. optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
  45. def train(epoch):
  46. total =0
  47. running_loss =0.0
  48. train_loss =0.0#记录每次epoch的损失
  49. accuracy =0#记录每次epoch的accuracyfor batch_id, data in enumerate(train_loader,0):
  50. inputs, target = data
  51. optimizer.zero_grad()# forword + backward + update
  52. outputs = model(inputs)
  53. loss = criterion(outputs, target)
  54. _, predicted = torch.max(outputs.data, dim=1)
  55. accuracy +=(predicted == target).sum().item()
  56. total += target.size(0)
  57. loss.backward()
  58. optimizer.step()
  59. running_loss += loss.item()
  60. train_loss = running_loss
  61. #每迭代300次,求一下这三百次迭代的平均if batch_id % 300==299:
  62. print('[%d, %5d] loss: %.3f' %(epoch+1, batch_id+1, running_loss / 300))
  63. running_loss =0.0
  64. print('第 %d epoch的 Accuracy on train set: %d %%, Loss on train set: %f' % (epoch + 1, 100 * accuracy / total, train_loss))#返回acclossreturn1.0 * accuracy / total, train_loss
  65. def validation(epoch):
  66. correct =0
  67. total =0
  68. val_loss =0.0
  69. with torch.no_grad():
  70. fordatain test_loder:
  71. images, target = data
  72. outputs = model(images)
  73. loss = criterion(outputs, target)
  74. val_loss += loss.item()
  75. _, predicted = torch.max(outputs.data, dim=1)
  76. total += target.size(0)
  77. correct +=(predicted == target).sum().item()
  78. print('第 %d epoch的 Accuracy on validation set: %d %%, Loss on validation set: %f' %(epoch+1,100*correct / total, val_loss))#返回acclossreturn1.0 * correct / total, val_loss
  79. #pytorch绘制loss和accuracy曲线
  80. def draw_fig(list,name,name2,epoch):
  81. # 我这里迭代了200次,所以x的取值范围为(0,200),然后再将每次相对应的准确率以及损失率附在x上
  82. x1 = range(1, epoch+1)
  83. print(x1)
  84. y1 = list
  85. ifname=="loss":
  86. plt.cla()
  87. plt.title('Train loss vs. epoch', fontsize=20)
  88. plt.plot(x1, y1, '.-')
  89. plt.xlabel('epoch', fontsize=20)
  90. plt.ylabel('Train loss', fontsize=20)
  91. plt.grid()
  92. str ="./lossAndacc/"+name2+"_loss.png"
  93. plt.savefig(str)
  94. plt.show()elif name =="acc":
  95. plt.cla()
  96. plt.title('Train accuracy vs. epoch', fontsize=20)
  97. plt.plot(x1, y1, '.-')
  98. plt.xlabel('epoch', fontsize=20)
  99. plt.ylabel('Train accuracy', fontsize=20)
  100. plt.grid()
  101. str2 ="./lossAndacc/" + name2 + "_accuracy.png"
  102. plt.savefig(str2)
  103. plt.show()
  104. def draw_in_one(list,epoch):
  105. # x_axix,train_pn_dis这些都是长度相同的list()# 开始画图
  106. x_axix =[x forxin range(1, epoch+1)]#把ranage转化为list
  107. train_acc = list[0]
  108. train_loss = list[1]
  109. val_acc = list[2]
  110. val_loss = list[3]#sub_axix = filter(lambda x: x % 200 == 0, x_axix)
  111. plt.title('Result Analysis')
  112. plt.plot(x_axix, train_acc, color='green', label='training accuracy')
  113. plt.plot(x_axix, train_loss, color='red', label='training loss')
  114. plt.plot(x_axix, val_acc, color='skyblue', label='val accuracy')
  115. plt.plot(x_axix, val_loss, color='blue', label='val loss')
  116. plt.legend()# 显示图例
  117. plt.xlabel('epoch times')
  118. plt.ylabel('rate')
  119. plt.show()# python 一个折线图绘制多个曲线if __name__ =='__main__':
  120. train_loss =[]
  121. train_acc =[]
  122. val_loss =[]
  123. val_acc =[]
  124. epoches =10
  125. list =[]forepochin range(epoches):
  126. acc1, loss1 = train(epoch)
  127. train_loss.append(loss1)
  128. train_acc.append(acc1)
  129. acc2, loss2 = validation(epoch)
  130. val_loss.append(loss2)
  131. val_acc.append(acc2)#四幅图分开绘制
  132. draw_fig(train_loss, "loss","train", epoches)
  133. draw_fig(train_acc, "acc", "train",epoches)
  134. draw_fig(val_loss, "loss","val", epoches)
  135. draw_fig(val_acc, "acc","val", epoches)# 四幅图合并绘制
  136. list.append(train_acc)
  137. list.append(train_loss)
  138. list.append(val_acc)
  139. list.append(val_loss)
  140. draw_in_one(list, epoches)

结果:

train acc
在这里插入图片描述
train loss
在这里插入图片描述
val acc
在这里插入图片描述

注:图的title代码中有误。读者自行更改

val loss
在这里插入图片描述

四幅图合并绘制

在这里插入图片描述

在计算这四个值时,代码可能有点小错误。导致画的图不很准确。读者发现后,自行更改吧

控制台输出内容:

  1. E:\anaconda3\envs\pytorch\python.exe D:/PycharmProjects/pytorchProject/手写数字识别.py
  2. [1, 300] loss: 2.211[1, 600] loss: 0.881[1, 900] loss: 0.439
  3. 1 epoch Accuracy on train set: 65 %, Loss on train set: 14.349343
  4. 1 epoch Accuracy on validation set: 89 %, Loss on validation set: 55.763730[2, 300] loss: 0.325[2, 600] loss: 0.284[2, 900] loss: 0.242
  5. 2 epoch Accuracy on train set: 91 %, Loss on train set: 8.700389
  6. 2 epoch Accuracy on validation set: 93 %, Loss on validation set: 34.062688[3, 300] loss: 0.199[3, 600] loss: 0.180[3, 900] loss: 0.159
  7. 3 epoch Accuracy on train set: 94 %, Loss on train set: 5.356741
  8. 3 epoch Accuracy on validation set: 94 %, Loss on validation set: 25.656663[4, 300] loss: 0.138[4, 600] loss: 0.131[4, 900] loss: 0.117
  9. 4 epoch Accuracy on train set: 96 %, Loss on train set: 4.067950
  10. 4 epoch Accuracy on validation set: 96 %, Loss on validation set: 19.429859[5, 300] loss: 0.110[5, 600] loss: 0.093[5, 900] loss: 0.095
  11. 5 epoch Accuracy on train set: 97 %, Loss on train set: 3.809268
  12. 5 epoch Accuracy on validation set: 96 %, Loss on validation set: 17.569023[6, 300] loss: 0.080[6, 600] loss: 0.082[6, 900] loss: 0.074
  13. 6 epoch Accuracy on train set: 97 %, Loss on train set: 3.285731
  14. 6 epoch Accuracy on validation set: 97 %, Loss on validation set: 14.668039[7, 300] loss: 0.062[7, 600] loss: 0.068[7, 900] loss: 0.064
  15. 7 epoch Accuracy on train set: 98 %, Loss on train set: 2.248924
  16. 7 epoch Accuracy on validation set: 97 %, Loss on validation set: 15.119584[8, 300] loss: 0.048[8, 600] loss: 0.055[8, 900] loss: 0.053
  17. 8 epoch Accuracy on train set: 98 %, Loss on train set: 2.621493
  18. 8 epoch Accuracy on validation set: 97 %, Loss on validation set: 13.119277[9, 300] loss: 0.042[9, 600] loss: 0.041[9, 900] loss: 0.047
  19. 9 epoch Accuracy on train set: 98 %, Loss on train set: 1.698503
  20. 9 epoch Accuracy on validation set: 97 %, Loss on validation set: 13.277307[10, 300] loss: 0.029[10, 600] loss: 0.037[10, 900] loss: 0.040
  21. 10 epoch Accuracy on train set: 98 %, Loss on train set: 1.292258
  22. 10 epoch Accuracy on validation set: 97 %, Loss on validation set: 13.084560
  23. range(1, 11)
  24. range(1, 11)
  25. range(1, 11)
  26. range(1, 11)
  27. Process finished with exit code 0

本文转载自: https://blog.csdn.net/t18438605018/article/details/122137737
版权归原作者 t18438605018 所有, 如有侵权,请联系我们删除。

“神经网络做MNIST手写数字识别代码”的评论:

还没有评论