1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
| import numpy import matplotlib.pyplot as plt import scipy.special import scipy.ndimage.interpolation import time import progressbar import matplotlib.animation as anim
class neuralNetwork: def __init__(self,inputnodes,hiddennodes,hiddennodes_2,outputnodes,learningrate): self.inodes = inputnodes self.hnodes = hiddennodes self.hnodes_2 = hiddennodes_2 self.onodes = outputnodes self.lr = learningrate self.wih = (numpy.random.rand(hiddennodes,inputnodes)-0.5) self.who = (numpy.random.rand(outputnodes,hiddennodes)-0.5) self.wih_ = numpy.random.normal(0.0,pow(self.hnodes,-0.5),(hiddennodes,inputnodes)) self.wh12_ = numpy.random.normal(0.0,pow(self.hnodes_2,0.5),(hiddennodes_2,hiddennodes)) self.who_ = numpy.random.normal(0.0,pow(self.onodes,-0.5),(outputnodes,hiddennodes_2))
self.activation_function = lambda x : scipy.special.expit(x)
def train(self,inputs_list,targets_list): inputs = numpy.array(inputs_list,ndmin=2).T targets = numpy.array(targets_list,ndmin=2).T
hidden_inputs = numpy.dot(self.wih_,inputs) hidden_outputs = self.activation_function(hidden_inputs)
hidden_inputs_2 = numpy.dot(self.wh12_,hidden_outputs) hidden_outputs_2 = self.activation_function(hidden_inputs_2) ''' # 第三隐藏层的输入信号: hidden_inputs_3 = numpy.dot(self.wh23_,hidden_outputs_2) # 第三隐藏层的输出信号: hidden_outputs_3 = self.activation_function(hidden_inputs_3) ''' final_inputs = numpy.dot(self.who_,hidden_outputs_2) final_outputs = self.activation_function(final_inputs)
output_errors = targets - final_outputs hidden_errors_2 = numpy.dot(self.who_.T,output_errors) hidden_errors = numpy.dot(self.wh12_.T,hidden_errors_2)
''' 优化链接权重值 ''' self.who_ += self.lr * numpy.dot((output_errors * final_outputs * (1.0 - final_outputs)),numpy.transpose(hidden_outputs_2)) self.wh12_ += self.lr * numpy.dot((hidden_errors_2 * hidden_outputs_2 * (1.0 - hidden_outputs_2)),numpy.transpose(hidden_outputs)) self.wih_ += self.lr * numpy.dot((hidden_errors * hidden_outputs * (1.0 - hidden_outputs)),numpy.transpose(inputs))
def query(self,inputs_list): inputs = numpy.array(inputs_list,ndmin=2).T self.hidden_inputs = numpy.dot(self.wih_,inputs) self.hidden_outputs = self.activation_function(self.hidden_inputs)
self.hidden_inputs_2 = numpy.dot(self.wh12_,self.hidden_outputs) self.hidden_outputs_2 = self.activation_function(self.hidden_inputs_2) ''' # 第三隐藏层的输入信号: self.hidden_inputs_3 = numpy.dot(self.wh23_,self.hidden_outputs_2) # 第三隐藏层的输出信号: self.hidden_outputs_3 = self.activation_function(self.hidden_inputs_3) ''' self.final_inputs = numpy.dot(self.who_,self.hidden_outputs_2) self.final_outputs = self.activation_function(self.final_inputs)
return self.final_outputs def test(Network,test_dataset_name): Network.wih_ = numpy.loadtxt('wih_file.csv') Network.wh12_ = numpy.loadtxt('wh12_file.csv') Network.who_ = numpy.loadtxt('who_file.csv')
test_data_file = open(test_dataset_name,'r') test_data_list = test_data_file.readlines() test_data_file.close()
print('\n') print("Testing...\n") correct_test = 0 all_test = 0 correct = [0,0,0,0,0,0,0,0,0,0] num_counter = [0,0,0,0,0,0,0,0,0,0]
p_test = progressbar.ProgressBar() p_test.start(len(test_data_list))
for imag_list in test_data_list: all_values = imag_list.split(',') lable = int(all_values[0]) scaled_input = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01 imag_array = numpy.asfarray(scaled_input).reshape((28,28)) ''' plt.imshow(imag_array,cmap='Greys',animated=True) plt.draw() plt.pause(0.00001) ''' net_answer = Network.query(scaled_input).tolist().index(max(Network.final_outputs)) num_counter[lable] += 1 if lable == int(net_answer): correct_test += 1 correct[lable] += 1 p_test.update(all_test + 1) all_test += 1
p_test.finish() print("Finish Test.\n")
performance = correct_test/all_test Per_num_performance = [] for i in range(10): try: Per_num_performance.append(correct[i]/num_counter[i]) except ZeroDivisionError: Per_num_performance.append(0)
print("The correctRate of per number: ",Per_num_performance) print("Performance of the NeuralNetwork: ",performance*100) return performance
input_nodes = 784 hidden_nodes = 700 hidden_nodes_2 = 700
output_nodes = 10 learningrate = 0.0001
if __name__ == "__main__":
epochs = 5
Net = neuralNetwork(input_nodes,hidden_nodes,hidden_nodes_2,output_nodes,learningrate)
data_file = open("mnist_train.csv",'r') data_list = data_file.readlines() N_train = len(data_list) data_file.close()
print("Training:", epochs, "epochs...") for e in range(epochs): print('\nThe '+str(e+1)+'th epoch trainning:\n') p_train = progressbar.ProgressBar() p_train.start(N_train) i = 0
for img_list in data_list: all_values = img_list.split(',') scaled_input = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01 imag_array = numpy.asfarray(scaled_input).reshape((28,28))
input_plus_10imag = scipy.ndimage.interpolation.rotate(imag_array,10,cval=0.01,reshape=False) input_minus_10imag = scipy.ndimage.interpolation.rotate(imag_array,-10,cval=0.01,reshape=False) input_plus10 = input_plus_10imag.reshape((1,784)) input_minus10 = input_minus_10imag.reshape((1, 784)) targets = numpy.zeros(output_nodes) + 0.01 targets[int(all_values[0])] = 0.99
Net.train(scaled_input,targets) Net.train(input_plus10,targets) Net.train(input_minus10,targets)
p_train.update(i+1) i+=1 p_train.finish() print("\nTrainning finish.\n")
numpy.savetxt('wih_file.csv',Net.wih_,fmt='%f') numpy.savetxt('wh12_file.csv',Net.wh12_,fmt='%f') numpy.savetxt('who_file.csv',Net.who_,fmt='%f')
|