当前位置:   article > 正文

基于前馈网络的手写数字识别系统_基于前馈神经网络的数字识别

基于前馈神经网络的数字识别

先看效果:

手写数字9识别测试

手写数字6识别测试

这个项目建立了一个含一个隐藏层(50个神经元)的前馈网络。对数字采用One-hot编码,因此输出层设置10个神经元;又因为mnist数据集中图像大小为28*28,故输入层设置784个神经元。将输入层到隐藏层、隐藏层到输出层的偏置整合到前一层的输出矩阵和两层间的权重矩阵上,则得到矩阵:

输入层:

其中n是训练集数据条数。采用批量梯度下降算法,则使用训练集全部六万条数据进行训练,n=60000。

第1,2层间权重矩阵:

两个矩阵做矩阵乘法并经sigmoid激活,得到n*50的矩阵,这是隐藏层的输出。随后在隐藏层最右侧一列追加全一列向量作为下一层偏置的系数,得到n*(50+1)的矩阵,作为输出层的输入。

第2层和第3层间的权值矩阵:

再做矩阵乘法,并经softmax沿1轴方向激活,得到n*10的矩阵。再对每个数以0.5为阈值转换成0和1,就可以得到预测出的One-hot编码,进行解码后即得到最终结果。

程序有train和test两个模式。在train模式中,每迭代100次,对权值矩阵进行一次存档。程序每次运行时都检查是否存在已经存档的权值矩阵和标签经one-hot编码后的矩阵,从而实现对每一次训练结果的保存。测试时为了速度只加载了前40个样本,这是可调的。在test模式中设置了一个加载图片的接口,配合windows自带的画图软件等,可以实现对自己手写的数字的识别。代码如下:

  1. import tensorflow as tf
  2. import numpy as np
  3. from scipy.io import savemat,loadmat
  4. import matplotlib.pyplot as plt
  5. import PIL.Image as img
  6. mnist=tf.keras.datasets.mnist
  7. print("data is loading...")
  8. (train_x,train_y),(test_x,test_y)=mnist.load_data()
  9. print("data loading finished.")
  10. r=tf.constant([[0,0,0,0,0,0,0,0,0,1],
  11. [1,0,0,0,0,0,0,0,0,0],
  12. [0,1,0,0,0,0,0,0,0,0],
  13. [0,0,1,0,0,0,0,0,0,0],
  14. [0,0,0,1,0,0,0,0,0,0],
  15. [0,0,0,0,1,0,0,0,0,0],
  16. [0,0,0,0,0,1,0,0,0,0],
  17. [0,0,0,0,0,0,1,0,0,0],
  18. [0,0,0,0,0,0,0,1,0,0],
  19. [0,0,0,0,0,0,0,0,1,0]])
  20. #编码和解码函数
  21. def one_hot(t_y):
  22. print("encoding...")
  23. for i in range(len(t_y)):
  24. if i==0:
  25. num=t_y[i]
  26. y=r[num,:]
  27. elif i==1:
  28. y=tf.stack([y,r[t_y[i],:]],axis=0)
  29. else:
  30. y=tf.concat([y,tf.reshape(r[t_y[i],:],[1,-1])],axis=0)
  31. print("encoding finished.")
  32. return y
  33. def decod(res):
  34. final=[]
  35. num=res.shape[0]
  36. for i in range(num):
  37. if all(res[i]==[0,0,0,0,0,0,0,0,0,1]):
  38. final.append(0)
  39. elif all(res[i]==[1,0,0,0,0,0,0,0,0,0]):
  40. final.append(1)
  41. elif all(res[i]==[0,1,0,0,0,0,0,0,0,0]):
  42. final.append(2)
  43. elif all(res[i]==[0,0,1,0,0,0,0,0,0,0]):
  44. final.append(3)
  45. elif all(res[i]==[0,0,0,1,0,0,0,0,0,0]):
  46. final.append(4)
  47. elif all(res[i]==[0,0,0,0,1,0,0,0,0,0]):
  48. final.append(5)
  49. elif all(res[i]==[0,0,0,0,0,1,0,0,0,0]):
  50. final.append(6)
  51. elif all(res[i]==[0,0,0,0,0,0,1,0,0,0]):
  52. final.append(7)
  53. elif all(res[i]==[0,0,0,0,0,0,0,1,0,0]):
  54. final.append(8)
  55. elif all(res[i]==[0,0,0,0,0,0,0,0,1,0]):
  56. final.append(9)
  57. else:
  58. final.append(-1) #太抽象以至于识别不出来的被标记为-1
  59. print("decoding finished.")
  60. return final
  61. try:
  62. open("C:\prog\matrix\y.mat")
  63. sv=loadmat("C:\prog\matrix\y.mat")
  64. y=tf.constant(sv["data"],dtype=tf.float32)
  65. except FileNotFoundError:
  66. y=one_hot(train_y)
  67. save_dict2={"name":"y","data":y}
  68. savemat("C:\prog\matrix\y.mat",save_dict2)
  69. first=len(train_y)
  70. x=tf.reshape(train_x,[first,-1])
  71. x=tf.cast(x,dtype=tf.float32)
  72. x=tf.concat([x,tf.ones([first,1],dtype=tf.float32)],axis=1)
  73. x=x-tf.reduce_mean(x)
  74. y=tf.cast(y,dtype=tf.float32)
  75. try:
  76. open("C:\prog\matrix\w12.mat")
  77. mid12=loadmat("C:\prog\matrix\w12.mat")
  78. w12=tf.constant(mid12["data"],dtype=tf.float32)
  79. print("w12 is loaded")
  80. except FileNotFoundError:
  81. w12=tf.random.uniform([28*28+1,50],dtype=tf.float32)
  82. print("w12 initialization finished")
  83. try:
  84. open("C:\prog\matrix\w23.mat")
  85. mid23=loadmat("C:\prog\matrix\w23.mat")
  86. w23=tf.constant(mid23["data"],dtype=tf.float32)
  87. print("w23 is loaded")
  88. except FileNotFoundError:
  89. w23=tf.random.uniform([50+1,10],dtype=tf.float32)
  90. print("w23 initialization finished")
  91. print("Train or test?")
  92. a=input()
  93. if a=="train":
  94. w12=tf.Variable(w12)
  95. w23=tf.Variable(w23)
  96. n=int(input("迭代次数:"))
  97. a=float(input("学习速率:"))
  98. ce=[]
  99. percentage=0
  100. counter=0
  101. print("processing...")
  102. for i in range(n):
  103. with tf.GradientTape(persistent=True) as tape:
  104. x2=tf.nn.sigmoid(tf.matmul(x,w12))
  105. x2=tf.concat([x2,tf.ones([first,1],dtype=tf.float32)],axis=1)
  106. logits=tf.matmul(x2,w23)
  107. Loss=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y,logits))
  108. ce.append(Loss)
  109. grad23=tape.gradient(Loss,w23)
  110. grad12=tape.gradient(Loss,w12) #这里偷了个懒,没有按权值分配Loss,但应该也可以达到目的
  111. w23.assign_sub(a*grad23)
  112. w12.assign_sub(a*grad12)
  113. del tape
  114. counter=counter+1
  115. if counter%100==0:
  116. dict_save_w12={"name":"w12","data":w12}
  117. savemat("C:\prog\matrix\w12.mat",dict_save_w12)
  118. dict_save_w23={"name":"w23","data":w23}
  119. savemat("C:\prog\matrix\w23.mat",dict_save_w23)
  120. if (counter/n*100)%5==0:
  121. percentage+=5
  122. print("proceeding:%%%d" %(percentage))
  123. print(Loss)
  124. #测试
  125. print("Training finished, testing started")
  126. tfirst=len(test_y[0:40])
  127. t_x=tf.reshape(test_x[0:40],[tfirst,-1])
  128. t_x=tf.cast(t_x,dtype=tf.float32)
  129. t_x=tf.concat([t_x,tf.ones([tfirst,1],dtype=tf.float32)],axis=1)
  130. t_x=t_x-tf.reduce_mean(t_x)
  131. tlog=tf.nn.sigmoid(tf.matmul(t_x,w12))
  132. tlog=tf.concat([tlog,tf.ones([tfirst,1],dtype=tf.float32)],axis=1)
  133. res=tf.nn.softmax(tf.matmul(tlog,w23),axis=1)
  134. print("decoding...")
  135. res=tf.where(res<0.5,0,1)
  136. final=np.array(decod(res))
  137. cor=final-test_y[0:40]
  138. coun=0
  139. for i in range(len(test_y[0:40])):
  140. if cor[i]==0:
  141. coun+=1
  142. rate=coun/len(test_y[0:40])
  143. print("Accuracy:%%%f" %(100*rate))
  144. print("Loss:%f" %Loss)
  145. print("Graph is loaded...")
  146. plt.rcParams["font.sans-serif"]="Microsoft Yahei"
  147. plt.figure()
  148. plt.subplot(1,2,1)
  149. plt.plot(ce)
  150. plt.title("平均交叉熵损失")
  151. plt.xlabel("迭代次数")
  152. plt.ylabel("Loss")
  153. plt.subplot(1,2,2)
  154. plt.plot(final,color="blue",label="识别结果")
  155. plt.plot(test_y,color="red",label="正确结果")
  156. plt.xlabel("测试样例序号")
  157. plt.xlim(0,30)
  158. plt.ylabel("数字")
  159. plt.title("测试结果")
  160. plt.suptitle("手写数字识别系统")
  161. plt.legend()
  162. plt.show()
  163. else:
  164. image=img.open("C:\prog\graph\g.png").convert("L")
  165. im=tf.constant(image,dtype=tf.float32)
  166. im=tf.reshape(im,[1,-1])
  167. im=tf.concat([im,tf.ones([1,1],dtype=tf.float32)],axis=1)
  168. lg=tf.nn.sigmoid(tf.matmul(im,w12))
  169. lg=tf.concat([lg,tf.ones([len(lg),1],dtype=tf.float32)],axis=1)
  170. res=tf.nn.softmax(tf.matmul(lg,w23))
  171. res=tf.where(res<0.5,0,1)
  172. finalres=decod(res)
  173. print(finalres)

经过了两天的花式调参,终于能够把Loss控制在0.23左右,训练好的权值矩阵放到了本文资源中。这个过程让我颇为感慨。多层神经网络的Loss不一定是凸函数,所以按梯度下降法进行权值修正的时候,Loss经常陷入局部极小值。在没有使用优化器的前提下,必须大胆把学习速率调大而不减小,试图让Loss从局部极小值里冲出来,当然成功与否取决于运气。这样反复了很多次,才最终把Loss下降到可观的范围。现在这个模型在测试集中的准确率可以达到92.5%。

ps:这个小项目是在不了解tensorflow自带的one-hot等函数的情况下写的,所以代码显得迂回冗长了很多,相较于用自带函数,做了一些更底层的实现。至于为什么没用小批量梯度下降,是因为一开始想先做批量梯度下降试试算法是否可行,后面懒得改了。此外,也没有用优化器,没有用sequential模型……要啥没啥。要啥没啥,但是能用

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

闽ICP备14008679号