9 神经网络深入
在第8章中,我们讲解了神经网络的初步认知,主要是理解了引入神经网络的意义及其前向传播过程。本章我们将进一步理解神经网络,理解它是如何自动优化参数,使其能完成分类、预测等功能的。
9.1 代价函数(Cost Function)
像之前讲解的线性回归和Logistic回归一样,涉及到优化参数的问题,我们必须求出该算法的代价函数。
假设有一组训练数据,,如果不考虑正则化的话,
对于线性回归,其代价函数为:
对于Logistic回归,其代价函数为:
对于神经网络,如果激活函数是Logistic的话,它的形式和Logistic回归有些类似。
假设:神经网络假设函数为K维向量,,则有:
9.2 反向传播
如上图,根据我们已经学习的神经网络前向传播,有:
前向传播只是不断地往后计算,最终给出分类的结果,但是,这个分类结果的正确性却没有保证,这时就要像之前的分类算法一样,通过减少误差,不断调整Θ(即权重)的值,保证得出的分类结果的正确性。这时候,科学家研究了一个算法完成这个任务,这个算法就是神经网络的后向传播。
神经网络的后向传播(Backpropagation)
我们设第l层,第j个单元的“误差”为 ,则对于上图的神经网路的后向传播为:
上式涉及到Logister的导数计算,这里进行简单的推导。
这样,当时,
后向传播是为了求解最优的权重参数的,那么怎么把前面的结合起来呢?
根据之前学过的线性回归和Logistic回归,要求解权重参数(θ),关键是求解出和。同样,在神经网络中也不例外。
神经网络中,之前提及到有J(Θ),为了之后的推到计算方便,我们这里做一个近似,,接着我们需要求解,下面我们分输出层和隐含层两部分进行简单的推导。
输出层:
输出层误差:计算误差反向传播的输出层的梯度和微分,用于更新输出层权值。
输出层的微分形式可以写成如下形式:
下面我们将上述偏导分左右推导,(这里我们矢量化表示,L表示神经网络的总层数)
左项推导,得到:
右项推导,得到:
将两项结合在一起,有:
当然,在视频中的输出层的更为简化,直接为:
隐含层
同理可得,
因此,如果使用梯度下降算法,则有:
这里的δ要对应相应的层,而η则类似学习速率,这里指的是网络设计参数。
9.3 编程实战
神经网络的数学理论相对之前的算法是更为复杂的,特别是后向传播。下面,我们结合具体的例子,编程实现神经网络,也许实战过后,对神经网络的认识会更加深刻具体。
这里,我们使用tensorflow神经网络框架,快速实现神经网络的构建。
下面是实战的全部代码:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
'''
Author: louishao
reference
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''
from __future__ import print_function
# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
import tensorflow as tf
# Parameters
learning_rate = 0.01
training_epochs = 200
batch_size = 100
display_step = 1
# Network Parameters
n_hidden_1 = 256 # 1st layer number of features
n_hidden_2 = 256 # 2nd layer number of features
n_input = 784 # MNIST data input (img shape: 28*28)
n_classes = 10 # MNIST total classes (0-9 digits)
# tf Graph input
x = tf.placeholder("float", [None, n_input])
y = tf.placeholder("float", [None, n_classes])
# Create model
def multilayer_perceptron(x, weights, biases):
# Hidden layer 1
layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
# Use sigmoid as activation
layer_1 = tf.nn.softmax(layer_1)
#layer_1 = tf.nn.relu(layer_1)
# Hidden layer 2
layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
layer_2 = tf.nn.softmax(layer_2)
#layer_2 = tf.nn.relu(layer_2)
# Output layer with linear activation
out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
return out_layer
# Store layers weight & bias
weights = {
'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))
}
biases = {
'b1': tf.Variable(tf.random_normal([n_hidden_1])),
'b2': tf.Variable(tf.random_normal([n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_classes]))
}
# Construct model
pred = multilayer_perceptron(x, weights, biases)
# Define loss and optimizer
# Define the cost function
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
# Gradient Descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
#optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# Initializing the variables
init = tf.initialize_all_variables()
# Launch the graph
with tf.Session() as sess:
sess.run(init)
# Training cycle
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
# Loop over all batches
for i in range(total_batch):
batch_x, batch_y = mnist.train.next_batch(batch_size)
# Run optimization op (backprop) and cost op (to get loss value)
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x,
y: batch_y})
# Compute average loss
avg_cost += c / total_batch
# Display logs per epoch step
if epoch % display_step == 0:
print("Epoch:", '%04d' % (epoch+1), "cost=", \
"{:.9f}".format(avg_cost))
print("Optimization Finished!")
# Test model
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
# Calculate accuracy
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))
上面代码完全按照了我们之前讲解的神经网络知识去编程。通过编程我们发现,该程序实现更好的方式是将激活函数改为RELU函数,将优化函数改为Adam优化,经过修改后,可以大大减少迭代数,从而提高程序的运行时间。
将修改前和修改后进行对比
修改前程序运行结果:
Extracting /tmp/data/train-images-idx3-ubyte.gz
Extracting /tmp/data/train-labels-idx1-ubyte.gz
Extracting /tmp/data/t10k-images-idx3-ubyte.gz
Extracting /tmp/data/t10k-labels-idx1-ubyte.gz
Epoch: 0001 cost= 2.348613948
Epoch: 0002 cost= 2.283615026
Epoch: 0003 cost= 2.260841895
Epoch: 0004 cost= 2.197613819
Epoch: 0005 cost= 2.097291337
Epoch: 0006 cost= 1.993323185
Epoch: 0007 cost= 1.850071414
Epoch: 0008 cost= 1.685328941
Epoch: 0009 cost= 1.546502026
Epoch: 0010 cost= 1.439334098
Epoch: 0011 cost= 1.349865329
Epoch: 0012 cost= 1.264136526
Epoch: 0013 cost= 1.187894512
Epoch: 0014 cost= 1.126270086
Epoch: 0015 cost= 1.076496551
Epoch: 0016 cost= 1.035493302
Epoch: 0017 cost= 1.001221116
Epoch: 0018 cost= 0.972048594
Epoch: 0019 cost= 0.948528574
Epoch: 0020 cost= 0.928471076
Epoch: 0021 cost= 0.910977629
Epoch: 0022 cost= 0.894381849
Epoch: 0023 cost= 0.879356768
Epoch: 0024 cost= 0.864971666
Epoch: 0025 cost= 0.852064942
Epoch: 0026 cost= 0.840678087
Epoch: 0027 cost= 0.828261544
Epoch: 0028 cost= 0.817391507
Epoch: 0029 cost= 0.807450493
Epoch: 0030 cost= 0.796776299
Epoch: 0031 cost= 0.786734011
......
(由于程序在我机子上运行太慢,所以没有等完全运行完,但可以看出迭代了30多次了)
修改后,
Extracting /tmp/data/train-images-idx3-ubyte.gz
Extracting /tmp/data/train-labels-idx1-ubyte.gz
Extracting /tmp/data/t10k-images-idx3-ubyte.gz
Extracting /tmp/data/t10k-labels-idx1-ubyte.gz
Epoch: 0001 cost= 176.073946022
Epoch: 0002 cost= 43.179293895
Epoch: 0003 cost= 27.394992440
Epoch: 0004 cost= 19.303700176
Epoch: 0005 cost= 14.132923727
Epoch: 0006 cost= 10.467257597
Epoch: 0007 cost= 7.971168485
Epoch: 0008 cost= 5.961594474
Epoch: 0009 cost= 4.604898651
Epoch: 0010 cost= 3.449496238
Epoch: 0011 cost= 2.749364777
Epoch: 0012 cost= 2.135642256
Epoch: 0013 cost= 1.607573424
Epoch: 0014 cost= 1.344761463
Epoch: 0015 cost= 0.958701863
Optimization Finished!
Accuracy: 0.947
(修改后,只需要迭代15次,就能得到不错的测试集准确率,而且运行速度还可以接受。)