32_mnistModelTraining.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. #!/usr/bin/env python
  2. #version : 2023.09.07
  3. #language : en
  4. import time
  5. from maix import camera, display, image
  6. import os
  7. import sys
  8. sys.path.append('/root/')
  9. from CocoPi import BUTTON
  10. key_A = BUTTON(14)
  11. key_B = BUTTON(8)
  12. key_C = BUTTON(13)
  13. key_D = BUTTON(7)
  14. #image.load_freetype("/root/preset/fonts/CascadiaCodePL-Italic.ttf")
  15. image.load_freetype("/root/preset/fonts/simhei.ttf")
  16. import numpy as np
  17. def sigmoid(x):
  18. return 1/(1+np.exp(-x))
  19. def grad(x):
  20. return x*(1-x)
  21. class NeuralNetwork:
  22. """
  23. 三层全连接前馈神经网络
  24. """
  25. def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate, active_function=sigmoid, gradient=grad, lambda_=0.1):
  26. """
  27. :param inputnodes: 输入层结点数
  28. :param hiddennodes: 隐藏层节点数
  29. :param outputnodes: 输出层节点数
  30. :param learningrate: 学习率
  31. :param active_function: 激活函数
  32. :param gradient: 激活函数的导数
  33. :param lambda_: L2正则化系数
  34. """
  35. self.inputnodes = inputnodes
  36. self.hiddennodes = hiddennodes
  37. self.outputnodes = outputnodes
  38. self.learningrate = learningrate
  39. self.active_function = active_function
  40. self.gradient = gradient
  41. self.lambda_ = lambda_
  42. # 权值矩阵
  43. self.weights_i_h = np.random.rand(
  44. self.hiddennodes, self.inputnodes) - 0.5
  45. self.weights_h_o = np.random.rand(
  46. self.outputnodes, self.hiddennodes) - 0.5
  47. def train_sgd(self, x, y):
  48. """梯度下降训练"""
  49. train_x = np.array(x).reshape(-1, 1)
  50. target = np.zeros((self.outputnodes, 1)) + 0.01
  51. target[y, 0] = 0.99
  52. hiddeninputs = np.dot(self.weights_i_h, train_x)
  53. hiddenoutputs = self.active_function(hiddeninputs)
  54. outputinputs = np.dot(self.weights_h_o, hiddenoutputs)
  55. final_outputs = self.active_function(outputinputs)
  56. error = target - final_outputs
  57. hidden_error = np.dot(self.weights_h_o.transpose(), error)
  58. self.weights_h_o += self.learningrate * error * \
  59. np.dot(self.gradient(final_outputs), hiddenoutputs.transpose())
  60. self.weights_i_h += self.learningrate * hidden_error * \
  61. np.dot(self.gradient(hiddenoutputs), train_x.transpose())
  62. def fit(self, train_x, targets):
  63. train_x = np.array(train_x)
  64. for i in range(train_x.shape[0]):
  65. self.train_sgd(train_x[i], targets[i])
  66. def query(self, inputs, debug=False):
  67. """单个值预测"""
  68. inputs = np.array(inputs).reshape(-1, 1)
  69. hidden_input = np.dot(self.weights_i_h, inputs)
  70. hidden_output = self.active_function(hidden_input)
  71. output_input = np.dot(self.weights_h_o, hidden_output)
  72. final_output = self.active_function(output_input)
  73. if debug:
  74. print('predict: ', final_output)
  75. return np.argmax(final_output)
  76. def predict(self, inputs):
  77. """批量预测"""
  78. res = []
  79. for x in inputs:
  80. res.append(self.query(x))
  81. return res
  82. def __str__(self):
  83. return "NeuralNetwork: \ninput_nodes = {0}, hidden_nodes = {1}, \noutputnodes = {2}, learningrate = {3}".format(
  84. self.inputnodes, self.hiddennodes, self.outputnodes, self.learningrate
  85. )
  86. test_df = np.loadtxt("/root/preset/training/res/mnist_test_10.csv", delimiter=",", dtype=str)
  87. test_df
  88. train_df = np.loadtxt("/root/preset/training/res/mnist_train_100.csv", delimiter=",", dtype=str)
  89. train_df
  90. # 用测试数据测试
  91. def accuracy(y_true, y_pred):
  92. """准确度"""
  93. y_true = np.array(y_true)
  94. y_pred = np.array(y_pred)
  95. return sum(y_true == y_pred)/y_true.shape[0]
  96. # 用全部数据进行训练
  97. def get_data():
  98. # train_df = np.loadtxt("mnist_train.csv", delimiter=",", dtype=str)
  99. # test_df = np.loadtxt("mnist_test.csv", delimiter=",", dtype=str)
  100. global train_df, test_df
  101. print(train_df.shape)
  102. print(test_df.shape)
  103. train_data = train_df.astype('int')
  104. train_x = train_data[:, 1:]
  105. train_y = train_data[:, 0]
  106. train_x = train_x / 255 * 0.99 + 0.01
  107. test_data = test_df.astype('int')
  108. test_x = test_data[:, 1:]
  109. test_y = test_data[:, 0]
  110. test_x = test_x / 255 * 0.99 + 0.01
  111. return train_x, train_y, test_x, test_y
  112. canvas = image.new(size=(320, 240),color = (15,21,46),mode = "RGB")
  113. #检查numpy.random模块是否已加载...
  114. canvas.draw_string(6, 8 , "Checking numpy module state...", scale = 1, color = (255,255,255), thickness = 2)
  115. display.show(canvas)
  116. if os.path.exists('/usr/lib/python3.8/site-packages/numpy/random/__init__.py'):
  117. canvas.draw_string(6, 28 , "Numpy.random module have't been loaded ...", scale = 1, color = (255,255,255), thickness = 2)
  118. display.show(canvas)
  119. canvas.draw_string(6, 48 , "Loading numpy.random module...", scale = 1, color = (255,255,255), thickness = 2)
  120. display.show(canvas)
  121. os.system('rm -rf /usr/lib/python3.8/site-packages/numpy/random/__init__.py')
  122. canvas.draw_string(6, 68 , "Loaded numpy.random module successfully!", scale = 1, color = (255,255,255), thickness = 2)
  123. display.show(canvas)
  124. canvas.draw_string(6, 88 , "The program will exit to complete configuration.", scale = 1, color = (255,255,255), thickness = 2)
  125. display.show(canvas)
  126. offTime=3
  127. while offTime:
  128. canvas.draw_rectangle(12, 108, 230, 127, color=(15,21,46),thickness=-1)
  129. canvas.draw_string(6, 108 , "The program will exit in {} seconds.".format(offTime), scale = 1, color = (255,255,255), thickness = 2)
  130. display.show(canvas)
  131. time.sleep(1)
  132. offTime=offTime-1
  133. else:
  134. canvas.draw_string(6, 28 , "Numpy.random module have been loaded ...", scale = 1, color = (255,255,255), thickness = 2)
  135. display.show(canvas)
  136. #如果未加载,选择提示...
  137. #如果已加载,显示Numpy已加载
  138. canvas.draw_string(6, 48 , "Building neural network training services...", scale = 1, color = (255,255,255), thickness = 2)
  139. display.show(canvas)
  140. #构建神经网络训练服务
  141. train_x, train_y, test_x, test_y = get_data()
  142. NN = NeuralNetwork(784, 100, 10, 0.3)
  143. NN.fit(train_x, train_y)
  144. y_pred = NN.predict(test_x)
  145. print("accuracy%.2f%%" % (100*accuracy(test_y, y_pred)))
  146. hiddennodes = [512, 256, 128]
  147. lrs = [0.1, 0.2, 0.3]
  148. for node in hiddennodes:
  149. for lr in lrs:
  150. NN = NeuralNetwork(784, node, 10, lr)
  151. NN.fit(train_x, train_y)
  152. y_pred = NN.predict(test_x)
  153. print("The number of hidden layer nodes%d,Learning rate%f,accuracy%.2f%%" %
  154. (node, lr, 100*accuracy(test_y, y_pred)))
  155. import pickle
  156. # 最佳参数
  157. # 隐藏层节点数128,学习率0.100000,准确度70.00%
  158. NN = NeuralNetwork(784, 128, 10, 0.1)
  159. #开启神经网络训练,记录时长
  160. # 训练10次,每3次训练下降一次学习率
  161. canvas.draw_string(6, 68 , "Start NN training for 10 training iterations...", scale = 1, color = (255,255,255), thickness = 2)
  162. display.show(canvas)
  163. for e in range(1, 11):
  164. if e % 3 == 0:
  165. NN.learningrate /= 2
  166. NN.fit(train_x, train_y)
  167. y_pred = NN.predict(test_x)
  168. #"第%d次训练,准确度%.2f%%"
  169. #文件已保存至
  170. canvas.draw_rectangle(6, 108, 319, 147, color=(15,21,46),thickness=-1)
  171. canvas.draw_string(6, 108 , "The %dth training,accuracy:%.2f%%" % (e, 100*accuracy(test_y, y_pred)), scale = 1, color = (209,72,54), thickness = 2)
  172. canvas.draw_string(6, 128 , 'Model file path:/root/user/model/NN{}.pkl'.format(e), scale = 1, color = (209,72,54), thickness = 2)
  173. display.show(canvas)
  174. print("The %d th training,accuracy%.2f%%" % (e, 100*accuracy(test_y, y_pred)))
  175. with open('/root/user/model/NN{}.pkl'.format(e), 'wb') as f: # 保存模型
  176. pickle.dump(pickle.dumps(NN), f)
  177. canvas.draw_string(6, 168 , "Model training completed!", scale = 1, color = (255,255,255), thickness = 2)
  178. display.show(canvas)
  179. os.system('touch /usr/lib/python3.8/site-packages/numpy/random/__init__.py')
  180. canvas.draw_string(6, 188 , "Numpy.random module have been unloaded ...", scale = 1, color = (255,255,255), thickness = 2)
  181. display.show(canvas)
  182. #训练已完成,是否要关闭numpy.random模块?
  183. #是,numpy.random模块已关闭,开机速度已优化
  184. #否,numpy.ramdom模块将持续占用系统内存,开机时将需要更多时间
  185. offTime=5
  186. while offTime:
  187. canvas.draw_rectangle(6, 208, 230, 227, color=(15,21,46),thickness=-1)
  188. canvas.draw_string(6, 208 , "The program will exit in {}seconds.".format(offTime), scale = 1, color = (255,255,255), thickness = 2)
  189. display.show(canvas)
  190. time.sleep(1)
  191. offTime=offTime-1