classneuralNetwork: # initialize the neural network def__init__(self, inputnodes, hiddennodes, outputnodes, learningrate): # set number of nodes in each input, hidden, output layer self.inNodes = inputnodes self.hidNodes = hiddennodes self.outNodes = outputnodes
# wih is the link weight matrix between hidden nodes and input nodes; # who is the link weight matrix between output nodes and hidden nodes; # w11 w21 # w12 w22 etc self.wih = numpy.random.normal(0.0, pow(self.hidNodes, -0.5), (self.hidNodes, self.inNodes)) self.who = numpy.random.normal(0.0, pow(self.outNodes, -0.5), (self.outNodes, self.hidNodes)) # learning rate self.lr = learningrate
# activation function is the sigmoid function self.activation_function = lambda x:scipy.special.expit(x)
# calculate signals into hidden layer hidden_inputs = numpy.dot(self.wih, inputs) # calculate the signals emerging from hidden layer hidden_outputs = self.activation_function(hidden_inputs)
# calculate signals into final output layer final_inputs = numpy.dot(self.who, hidden_outputs) # calculate the signals emerging from final output layer final_outputs = self.activation_function(final_inputs) # output layer error is the (target - acture) output_errors = targets - final_outputs # hidden layer error is the output_errors, split by weights, recombined at hidden nodes hidden_errors = numpy.dot(self.who.T, output_errors)
# update the weights for the links between the hidden and output layers self.who += self.lr * numpy.dot((output_errors * final_outputs * (1.0 - final_outputs)), numpy.transpose(hidden_outputs))
# update the weights for the links between the input and hidden layers self.wih += self.lr * numpy.dot((hidden_errors * hidden_outputs * (1.0 - hidden_outputs)), numpy.transpose(inputs))
查询函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
defquery(self, inputs_list): # convert inputs list to 2d array inputs = numpy.array(inputs_list, ndmin = 2).T
# calculate signals into hidden layer hidden_inputs = numpy.dot(self.wih, inputs) # calculate the signals emerging from hidden layer hidden_outputs = self.activation_function(hidden_inputs)
# calculate signals into final output layer final_inputs = numpy.dot(self.who, hidden_outputs) # calculate the sognals emerging from final output layer final_outputs = self.activation_function(final_inputs)
for e in range(epochs): for record in training_data_list: all_values = record.split(',') inputs = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01 targets = numpy.zeros(output_nodes) + 0.01 targets[int(all_values[0])] = 0.99 n.train(inputs, targets)
# 从初始化文件读取权重矩阵wih、who wih = [[] for i in range(hidden_nodes)] who = [[] for i in range(output_nodes)] with open('weight.csv', 'r') as fr: fr_csv = csv.reader(fr) k = 0 for row in fr_csv: if k <= hidden_nodes - 1: wih[k] = list(map(float, row)) else: who[k-hidden_nodes] = list(map(float, row)) k += 1
# 数值预处理 # our_own_dataset为各个图像预处理后数据的集合 # our_own_dataset中各个元素为一个record,包括正确的标签和图像数据 our_own_dataset = [] for image_file_name in glob.glob('?.png'): print ("loading ... ", image_file_name) # use the filename to set the correct label label = int(image_file_name[-5:-4]) # load image data from png files into an array img_array = imageio.imread(image_file_name, as_gray=True) # reshape from 28x28 to list of 784 values, invert values img_data = 255.0 - img_array.reshape(784) # then scale data to range from 0.01 to 1.0 img_data = (img_data / 255.0 * 0.99) + 0.01 print(numpy.min(img_data)) print(numpy.max(img_data)) # append label and image data to test data set record = numpy.append(label,img_data) print(record) our_own_dataset.append(record) pass
最后,进行识别:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# 初始化 neural_network = Use.initialize()
# 测试 scorecard = [] for record in our_own_dataset: all_values = record correct_label = int(all_values[0]) print(correct_label, "is correct label") inputs = numpy.asfarray(all_values[1:]) outputs = neural_network.query(inputs) label = numpy.argmax(outputs) print(label, "is network's answer\n") if label == correct_label: scorecard.append(1) else: scorecard.append(0) scorecard_array = numpy.asarray(scorecard) print("performance = {}".format(scorecard_array.sum() / scorecard_array.size))