32_mnistModelTraining.py 8.8 KB

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