深度学习和神经网络对很多初学者来说都是摸不着头脑,今天分享一个完整的手写识别的实例,学习和理解了这个实例代码和过程就基本上掌握了神经网络。


1、构建神经网络类  network_claas.py


  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3.  
  4. # neural network class definition
  5. import scipy.special
  6. import numpy 
  7. # library for plotting arrays
  8. import matplotlib.pyplot
  9. # helper to load data from PNG image files# helpe 
  10. import imageio
  11. # glob helps select multiple files using patterns
  12. import glob
  13.  
  14. class neuralNetwork : 
  15.     
  16.     # initialise the neural network 
  17.     def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate) : 
  18.         
  19.         #set number of nodes in each input , hidden , output
  20.         #初始化网络,设置输入层,中间层,和输出层节点数
  21.         self.inodes = inputnodes
  22.         self.hnodes = hiddennodes
  23.         self.onodes = outputnodes
  24.  
  25.         # link weight matrices, wih and who 
  26.         # weights inside the arrays are w_ i_ j, where link is from node i to node j in the next layer 
  27.         # w11 w21 
  28.         # w12 w22 etc 
  29.         # 初始化权重矩阵,我们有两个权重矩阵,一个是wih表示输入层和中间层节点间链路权重形成的矩阵一个是who,表示中间层和输出层间链路权重形成的矩阵
  30.         self. wih = numpy.random.normal( 0.0, pow( self. hnodes, -0.5), (self. hnodes, self. inodes))
  31.         self. who = numpy.random.normal( 0.0, pow( self. onodes, -0.5), (self. onodes, self. hnodes))
  32.  
  33.         # learning rate 
  34.         self.lr = learningrate
  35.  
  36.         # activation function is the sigmoid function
  37.         # 设置激活函数的反函数
  38.         self.activation_function = lambda x:scipy.special.expit(x) 
  39.  
  40.         pass 
  41.     
  42.     # train the neural network 
  43.     def train(self, inputs_list, targets_list) : 
  44.  
  45.         # convert inputs list to 2d array
  46.         #根据输入的训练数据更新节点链路权重
  47.         #把inputs_list, targets_list转换成numpy支持的二维矩阵.T表示做矩阵的转置
  48.         inputs = numpy.array(inputs_list, ndmin=2).T
  49.         targets = numpy.array(targets_list, ndmin=2).T
  50.         
  51.         # calculate signals into hidden layer
  52.         #计算信号经过输入层后产生的信号量
  53.         hidden_inputs = numpy.dot(self.wih, inputs)
  54.         # calculate the signals emerging from hidden layer
  55.         #中间层神经元对输入的信号做激活函数后得到输出信号
  56.         hidden_outputs = self.activation_function(hidden_inputs)
  57.         
  58.         # calculate signals into final output layer
  59.         #输出层接收来自中间层的信号量
  60.         final_inputs = numpy.dot(self.who, hidden_outputs)
  61.         # calculate the signals emerging from final output layer
  62.         #输出层对信号量进行激活函数后得到最终输出信号
  63.         final_outputs = self.activation_function(final_inputs)
  64.         
  65.         # output layer error is the (target - actual)
  66.         #计算误差
  67.         output_errors = targets - final_outputs
  68.         # hidden layer error is the output_errors, split by weights, recombined at hidden nodes
  69.         hidden_errors = numpy.dot(self.who.T, output_errors) 
  70.         
  71.         #根据误差计算链路权重的更新量,然后把更新加到原来链路权重上
  72.         # update the weights for the links between the hidden and output layers
  73.         self.who += self.lr * numpy.dot((output_errors * final_outputs * (1.0 - final_outputs)), numpy.transpose(hidden_outputs))
  74.         
  75.         # update the weights for the links between the input and hidden layers
  76.         self.wih += self.lr * numpy.dot((hidden_errors * hidden_outputs * (1.0 - hidden_outputs)), numpy.transpose(inputs))
  77.         pass 
  78.     
  79.     # query the neural network 
  80.     def query(self, inputs_list) : 
  81.  
  82.         #根据输入数据计算并输出答案
  83.         # convert inputs list to 2d array
  84.         inputs = numpy.array(inputs_list, ndmin=2).T
  85.  
  86.         #计算中间层从输入层接收到的信号量
  87.         # calculate signals into hidden layer
  88.         hidden_inputs = numpy.dot(self.wih, inputs)
  89.  
  90.         #计算中间层经过激活函数后形成的输出信号量
  91.         # calculate the signals emerging from hidden layer
  92.         hidden_outputs = self.activation_function(hidden_inputs)
  93.         
  94.         #计算最外层接收到的信号量
  95.         # calculate signals into final output layer
  96.         final_inputs = numpy.dot(self.who, hidden_outputs)
  97.         # calculate the signals emerging from final output layer
  98.         final_outputs = self.activation_function(final_inputs)
  99.         
  100.         return final_outputs



2、初始化及训练测试该网络


  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3.  
  4. from network_claas import neuralNetwork
  5. import numpy
  6. import matplotlib
  7. import glob
  8. import imageio 
  9. # library for plotting arrays
  10. import matplotlib.pyplot as plt
  11. import pylab
  12.  
  13. # ensure the plots are inside this notebook, not an external window
  14.  
  15. #初始化网络
  16. # number of input, hidden and output nodes
  17. input_nodes = 784
  18. hidden_nodes = 100
  19. output_nodes = 10
  20.  
  21.  
  22. #初始化学习率
  23. # learning rate is 0.3
  24. learning_rate = 0.3
  25.  
  26.  
  27. # create instance of neural network
  28. # 初始化神经网络
  29. = neuralNetwork(input_nodes,hidden_nodes,output_nodes, learning_rate)
  30.  
  31. # load the mnist training data CSV file into a list 
  32. training_data_file = open("mnist_dataset/mnist_train_100.csv", 'r') 
  33. training_data_list = training_data_file.readlines() 
  34. training_data_file.close()
  35.  
  36. # train the neural network 
  37. # epochs is the number of times the training data set is used for training 
  38. epochs = 5 
  39.  
  40. for e in range( epochs): 
  41.  
  42.     # go through all records in the training data set 
  43.  
  44.     for record in training_data_list: 
  45.         # split the record by the ',' commas 
  46.         all_values = record.split(',') 
  47.         # scale and shift the inputs 
  48.         inputs = (numpy.asfarray( all_values[1:]) / 255.0 * 0.99) + 0.01 
  49.         # create the target output values (all 0.01, except the desired label which is 0.99) 
  50.         targets = numpy.zeros(output_nodes) + 0.01 
  51.         # all_values[0] is the target label for this record
  52.  
  53.         targets[int(all_values[0])] = 0.99 
  54.         n.train(inputs, targets) 
  55.     pass 
  56.  
  57.  # load the mnist test data CSV file into a list 
  58. test_data_file = open("mnist_dataset/mnist_test_10.csv", 'r') 
  59. test_data_list = test_data_file.readlines() 
  60. test_data_file.close() 
  61.  
  62. # test the neural network 
  63. # scorecard for how well the network performs, initially empty 
  64. scorecard = [] 
  65.  
  66. # go through all the records in the test data set 
  67. for record in test_data_list: 
  68.     # split the record by the ',' commas 
  69.     all_values = record.split(',') 
  70.     # correct answer is first value 
  71.     correct_label = int( all_values[ 0]) 
  72.     # scale and shift the inputs 
  73.     inputs = (numpy.asfarray( all_values[ 1:]) / 255.0 * 0.99) + 0.01 
  74.     # query the network 
  75.     outputs = n.query( inputs) 
  76.     # the index of the highest value corresponds to the label 
  77.     label = numpy.argmax( outputs) 
  78.     # append correct or incorrect to list 
  79.     if (label == correct_label): 
  80.         # network' s answer matches correct answer, add 1 to scorecard 
  81.         scorecard.append( 1) 
  82.     else: 
  83.         # network' s answer doesn' t match correct answer, add 0 to scorecard 
  84.         scorecard.append( 0) 
  85.         pass 
  86.     pass 
  87.  
  88. # calculate the performance score, the fraction of correct answers 
  89. scorecard_array = numpy.asarray( scorecard) 
  90. print ("performance = ", scorecard_array.sum() / scorecard_array.size)
  91.  
  92.  
  93. # our own image test data set# our o 
  94. our_own_dataset = []
  95.  
  96. # load the png image data as test data set
  97. for image_file_name in glob.glob('my_own_images/2828_my_own_?.png'):
  98.     
  99.     # use the filename to set the correct label
  100.     label = int(image_file_name[-5:-4])
  101.     
  102.     # load image data from png files into an array
  103.     print ("loading ... ", image_file_name)
  104.     img_array = imageio.imread(image_file_name, as_gray=True)
  105.     
  106.     # reshape from 28x28 to list of 784 values, invert values
  107.     img_data  = 255.0 - img_array.reshape(784)
  108.     
  109.     # then scale data to range from 0.01 to 1.0
  110.     img_data = (img_data / 255.0 * 0.99) + 0.01
  111.     print(numpy.min(img_data))
  112.     print(numpy.max(img_data))
  113.     
  114.     # append label and image data  to test data set
  115.     record = numpy.append(label,img_data)
  116.     our_own_dataset.append(record)
  117.     
  118.     pass
  119.  
  120. # record to test
  121. item = 2
  122.  
  123. # plot image
  124. plt.imshow(our_own_dataset[item][1:].reshape(28,28), cmap='Greys', interpolation='None')
  125.  
  126. # correct answer is first value
  127. correct_label = our_own_dataset[item][0]
  128.  
  129. # data is remaining values
  130. inputs = our_own_dataset[item][1:]
  131.  
  132. # query the network
  133. outputs = n.query(inputs)
  134. print (outputs)
  135.  
  136. # the index of the highest value corresponds to the label
  137. label = numpy.argmax(outputs)
  138. print("network says ", label)
  139. # append correct or incorrect to list
  140. if (label == correct_label):
  141.     print ("match!")
  142. else:
  143.     print ("no match!")
  144.     pass
  145.  
  146. pylab.show()



3,输出如下:


image.png


4,完整代码如下:


下载.png PythonApplicationNetwork.zip