梳理了全连接神经网络模型前向传播和反向传播的工作流程步骤,仅为入门学习用,实际应用应采用TensorFlow等其他框架
数据集下载链接: 训练集:https://pjreddie.com/media/files/mnist_train.csv 测试集:https://pjreddie.com/media/files/mnist_test.csv
环境:Python3.8
import numpy
import scipy.special
class neuralNetwork:
def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate):
self.inodes = inputnodes
self.hnodes = hiddennodes
self.onodes = outputnodes
self.wih = numpy.random.normal(0, pow(self.hnodes, -0.5), (self.hnodes, self.inodes))
self.who = numpy.random.normal(0, pow(self.hnodes, -0.5), (self.onodes, self.hnodes))
self.lr = learningrate
self.activation_fuction = lambda x: scipy.special.expit(x)
pass
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_fuction(hidden_inputs)
final_inputs = numpy.dot(self.who, hidden_outputs)
final_outputs = self.activation_fuction(final_inputs)
output_errors = targets - final_outputs
hidden_errors = numpy.dot(self.who.T, output_errors)
self.who += self.lr * numpy.dot((output_errors * final_outputs * (1 - final_outputs)),
numpy.transpose(hidden_outputs))
self.wih += self.lr * numpy.dot((hidden_errors * hidden_outputs * (1 - hidden_outputs)),
numpy.transpose(inputs))
pass
def query(self, inputs_list):
inputs = numpy.array(inputs_list, ndmin=2).T
hidden_nodes = numpy.dot(self.wih, inputs)
hidden_outputs = self.activation_fuction(hidden_nodes)
final_inputs = numpy.dot(self.who, hidden_outputs)
final_outputs = self.activation_fuction(final_inputs)
return final_outputs
pass
input_nodes = 784
hidden_nodes = 100
output_nodes = 10
learning_rate = 0.3
n = neuralNetwork(input_nodes, hidden_nodes, output_nodes, learning_rate)
traning_data_file=open("mnist_dataset/mnist_train.csv",'r')
traning_data_list=traning_data_file.readlines()
traning_data_file.close()
for record in traning_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)
test_data_file=open("mnist_dataset/mnist_test.csv",'r')
test_list=test_data_file.readlines()
test_data_file.close()
scorecard=[]
for record in test_list:
all_values = record.split(',')
correct_label=int(all_values[0])
print(correct_label,"correct_label")
inputs=(numpy.asfarray(all_values[1:])/255.0*0.99)+0.01
outputs=n.query(inputs)
label=numpy.argmax(outputs)
print(label,"networ's answer")
if(label==correct_label):
scorecard.append(1)
else:
scorecard.append(0)
scorecard_array=numpy.asarray(scorecard)
print("performance:",scorecard_array.sum()/scorecard_array.size)
|