神经网络基本编程
采用Sigmod激活函数,建立一个包含一层隐藏层的神经网络通用代码:
import numpy
# scipy.special for the sigmoid function expit()
import scipy.special
class neuralNetwork:
# initialise the neural network
def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate):
# set number of nodes in each input, hidden, output layer
self.inodes = inputnodes
self.hnodes = hiddennodes
self.onodes = outputnodes
# link weight matrices, wih and who
# weights inside the arrays are w_i_j, where link is from node i to node j in the next layer
# w11 w21
# w12 w22 etc
self.wih = numpy.random.normal(0.0, pow(self.inodes, -0.5), (self.hnodes, self.inodes))
self.who = numpy.random.normal(0.0, pow(self.hnodes, -0.5), (self.onodes, self.hnodes))
# learning rate
self.lr = learningrate
# activation function is the sigmoid function
self.activation_function = lambda x: scipy.special.expit(x)
# train the neural network
def train(self, inputs_list, targets_list):
# convert inputs list to 2d array
inputs = numpy.array(inputs_list, ndmin=2).T
targets = numpy.array(targets_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 signals emerging from final output layer
final_outputs = self.activation_function(final_inputs)
# output layer error is the (target - actual)
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))
# query the neural network
def query(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 signals emerging from final output layer
final_outputs = self.activation_function(final_inputs)
return final_outputs
# number of input, hidden and output nodes
input_nodes = 3
hidden_nodes = 3
output_nodes = 3
# learning rate is 0.3
learning_rate = 0.3
# create instance of neural network
n = neuralNetwork(input_nodes,hidden_nodes,output_nodes, learning_rate)
n.query([1.0, 0.5, -1.5])
这里神经网络的训练是基于梯度下降的算法的。通过误差的反向传递最终得到一个最优解。公式为:
$$
w_{jk} = w_{jk} - \alpha \frac{dE}{dw_{jk}}
$$
$$
E = \sum_n (t_n - o_n)^2
$$
其中α代表学习率,决定了训练的速度。后面的求导代表$w_{jk}$在误差中的梯度,通过这个式子可以使得输出的值和真实值相比误差不断减小。算得
$$
\frac{dE}{dw_{jk}} = - 2(t_k - o_k) * sigmoid(\sum_j w_{jk}o_j)(1-sigmoid(\sum_j w_{jk}o_j)) * o_j
$$
其中$t_k$为该权重对应输出节点的真实值,$o_k$为现在该输出节点预测值,$o_j$是隐藏层的输出值。可以写成:
$$
\frac{dE}{dw_{jk}} = - e_k * sigmoid(\sum_j w_{jk}o_j)(1-sigmoid(\sum_j w_{jk}o_j)) * o_j
$$
$$
\Delta w_{jk} = \alpha * \frac{dE}{dw_{jk}}
$$
可以看到更新的权重矩阵的梯度是一个一维的列向量乘以一维行向量。
识别手写数字
代码及相关资源来源:https://www.epubit.com/bookDetails?id=N34292&typeName=%E6%90%9C%E7%B4%A2
https://link.zhihu.com/?target=http%3A//www.pjreddie.com/media/files/mnist_train.csv
https://link.zhihu.com/?target=http%3A//www.pjreddie.com/media/files/mnist_test.csv
数据用CSV文件存放,数字是28*28像素,每行第一个值是标签,后面的都是灰度值。训练集有100条,测试集10条。
样式展示:
代码:
import numpy
# scipy.special for the sigmoid function expit()
import scipy.special
# library for plotting arrays
import matplotlib.pyplot
# ensure the plots are inside this notebook, not an external window
%matplotlib inline
--snip--
# number of input, hidden and output nodes
input_nodes = 784
hidden_nodes = 200
output_nodes = 10
# learning rate
learning_rate = 0.1
# create instance of neural network
n = neuralNetwork(input_nodes,hidden_nodes,output_nodes, learning_rate)
# load the mnist training data CSV file into a list
training_data_file = open("mnist_dataset/mnist_train.csv", 'r')
training_data_list = training_data_file.readlines()
training_data_file.close()
# train the neural network
# epochs is the number of times the training data set is used for training
epochs = 10
for e in range(epochs):
# go through all records in the training data set
for record in training_data_list:
# split the record by the ',' commas
all_values = record.split(',')
# scale and shift the inputs
inputs = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
# create the target output values (all 0.01, except the desired label which is 0.99)
targets = numpy.zeros(output_nodes) + 0.01
# all_values[0] is the target label for this record
targets[int(all_values[0])] = 0.99
n.train(inputs, targets)
# load the mnist test data CSV file into a list
test_data_file = open("mnist_dataset/mnist_test.csv", 'r')
test_data_list = test_data_file.readlines()
test_data_file.close()
# scorecard for how well the network performs, initially empty
scorecard = []
# go through all the records in the test data set
for record in test_data_list:
# split the record by the ',' commas
all_values = record.split(',')
# correct answer is first value
correct_label = int(all_values[0])
# scale and shift the inputs
inputs = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
# query the network
outputs = n.query(inputs)
# the index of the highest value corresponds to the label
label = numpy.argmax(outputs)
# append correct or incorrect to list
if (label == correct_label):
# network's answer matches correct answer, add 1 to scorecard
scorecard.append(1)
else:
# network's answer doesn't match correct answer, add 0 to scorecard
scorecard.append(0)
# calculate the performance score, the fraction of correct answers
scorecard_array = numpy.asarray(scorecard)
print ("performance = ", scorecard_array.sum() / scorecard_array.size)
要注意的点:
这里输入节点为28*28=784,输出节点为10个,分别代表0到9这10个数字,那个输出节点数值最大那么分类结果就是这个数字。
激活函数不可能产生0或1的输出。因此需要使用0.01和0.99代替0和1。因此训练目标是让除了目标输出节点为0.99,其他节点为0.01。
查看图片的代码为
image_array = numpy.asfarray(all_values[1:]).reshape((28,28)) matplotlib.pyplot.imshow(image_array, cmap='Greys', interpolation='None')
过高和过低的学习率都是有害的。过高会使得在梯度下降的过程中的来回震动加剧,难以找到最优点。过低会导致学习缓慢,迟迟达不到最优点。
多次运行会因为初始点的不同,得到不同的结果,这就是多个局部的最优点,我们从这些最优点中,挑选最好的即可。
过多的训练会过犹不及,出现过拟合现象,导致网络在新数据上表现不佳。
改变隐藏层的节点数目可以优化训练结果,过少的隐藏节点会使得网络学习能力不足,过多会使得网络难以训练。
识别自己手写的数字
我们可以尝试着自己的笔迹,或者是故意做一些扭曲和噪声的处理,来测试网络的辨别能力。当我们得到这种图片后首先需要把它们处理成28*28像素的图片,你可以使用图像编辑器做到这一点,然后要转换成灰度数字表现的形式代码如下:
import scipy.misc
img_array = scipy.misc.imread(image_file_name,flatten = True)
img_data = 255.0 - img_array.reshape(784)
img_data = (img_data / 255.0 * 0.99) + 0.01
其中imread函数从图像文件中读取数据,”flatten=True”把图像变成简单的浮点数数组。如果图像是彩色的,颜色值会自动转换为灰度值。这样就可以把这些数据运用到我们的模型中了。
旋转图像可以创建新的训练数据
收集更多的手写样本固然可以提高模型的准确率,但是工作量太大了。一个很好的做法是通过顺时针或逆时针旋转它们,可以创建新的样本,通过这些新的样本进行训练,同样可以很好地提高模型的准确率。但要注意旋转的角度不能过大,否则会降低神经网络的性能,因为这意味创建了不能代表数字的图像,建议旋转10°,这个角度比较理想。同样的,我们在识别其他有关物体的图片时也可以进行左右翻转或者放大的操作来创造更多地样本。
ndimage.interpolation.rotate()可以将数组转过一个角度:
inputs_plus10_img = scipy.ndimage.interpolation.rotate(scaled_input.reshape(28,28),10,cval=0.0,reshape=False)
原来的numpy数字被重新转换成28*28的数组后,逆时针旋转10度,reshape=false可以防止将图像压扁。cval= 0意思是用零来填补旋转后多出的空白部分。把在源代码上加几行就行了。
for e in range(epochs):
# go through all records in the training data set
for record in training_data_list:
# split the record by the ',' commas
all_values = record.split(',')
# scale and shift the inputs
inputs = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
# create the target output values (all 0.01, except the desired label which is 0.99)
targets = numpy.zeros(output_nodes) + 0.01
# all_values[0] is the target label for this record
targets[int(all_values[0])] = 0.99
n.train(inputs, targets)
## create rotated variations
# rotated anticlockwise by x degrees
inputs_plusx_img = scipy.ndimage.interpolation.rotate(inputs.reshape(28,28), 10, cval=0.01, order=1, reshape=False)
n.train(inputs_plusx_img.reshape(784), targets)
# rotated clockwise by x degrees
inputs_minusx_img = scipy.ndimage.interpolation.rotate(inputs.reshape(28,28), -10, cval=0.01, order=1, reshape=False)
n.train(inputs_minusx_img.reshape(784), targets)
# rotated anticlockwise by 10 degrees
#inputs_plus10_img = scipy.ndimage.interpolation.rotate(inputs.reshape(28,28), 10, cval=0.01, order=1, reshape=False)
#n.train(inputs_plus10_img.reshape(784), targets)
# rotated clockwise by 10 degrees
#inputs_minus10_img = scipy.ndimage.interpolation.rotate(inputs.reshape(28,28), -10, cval=0.01, order=1, reshape=False)
#n.train(inputs_minus10_img.reshape(784), targets)
pass
pass