Post Views: 310
深度神经网络(Deep Neural Networks,DNN)可以理解为有很多隐藏层的神经网络,又被称为深度前馈网络,多层感知机。
本实验介绍深层神经网络在 TensorFlow 上的实现,并使用模型处理 MNIST 数据集。
一个两层的深层神经网络结构如下:
MNIST 是一个手写阿拉伯数字的数据集。
其中包含有 60000 个已经标注了的训练集,还有 10000 个用于测试的测试集。
MNIST包含四个文件案,分别为
名称 |
---|
t10k-images-idx3-ubyte.gz |
t10k-labels-idx1-ubyte.gz |
train-images-idx3-ubyte.gz |
train-labels-idx1-ubyte.gz |
不一样 的是我们可以通过调整深度神经网络的层次来看看能不能达到不一样的效果。
使用以下的命令进行下载:
下载 train-images-idx3-ubyte.gz( 训练集图片,55000张训练集,5000张验证集 )
wget http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz
下载 train-labels-idx1-ubyte.gz( 训练集图片对应的标签 )
wget http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz
下载 t10k-images-idx3-ubyte.gz( 测试集图片,10000张图片 )
wget http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz
下载 t10k-labels-idx1-ubyte.gz( 测试集图片对应的标签 )
wget http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz
现在您可以在 /home/ubuntu 目录下创建源文件 deep_neural_networks.py
touch deep_neural_networks.py
编辑 deep_neural_networks.py ,内容可参考:
deep_neural_networks.py
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
def add_layer(inputs, in_size, out_size, activation_function=None):
W = tf.Variable(tf.random_normal([in_size, out_size]))
b = tf.Variable(tf.zeros([1, out_size]) + 0.01)
Z = tf.matmul(inputs, W) + b
if activation_function is None:
outputs = Z
else:
outputs = activation_function(Z)
return outputs
if __name__ == "__main__":
MNIST = input_data.read_data_sets("mnist", one_hot=True)
learning_rate = 0.01
batch_size = 128
n_epochs = 70
X = tf.placeholder(tf.float32, [batch_size, 784])
Y = tf.placeholder(tf.float32, [batch_size, 10])
layer_dims = [784, 500, 500, 10]
layer_count = len(layer_dims)-1
layer_iter = X
for l in range(1, layer_count): # layer [1,layer_count-1] is hidden layer
layer_iter = add_layer(layer_iter, layer_dims[l-1], layer_dims[l], activation_function=tf.nn.relu)
prediction = add_layer(layer_iter, layer_dims[layer_count-1], layer_dims[layer_count], activation_function=None)
entropy = tf.nn.softmax_cross_entropy_with_logits(labels=Y, logits=prediction)
loss = tf.reduce_mean(entropy)
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
init = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
n_batches = int(MNIST.test.num_examples/batch_size)
for i in range(n_epochs):
for j in range(n_batches):
X_batch, Y_batch = MNIST.train.next_batch(batch_size)
_, loss_ = sess.run([optimizer, loss], feed_dict={X: X_batch, Y: Y_batch})
if i % 10 == 5 and j == 0:
print "Loss of epochs[{0}]: {1}".format(i, loss_)
# test the model
n_batches = int(MNIST.test.num_examples/batch_size)
total_correct_preds = 0
for i in range(n_batches):
X_batch, Y_batch = MNIST.test.next_batch(batch_size)
preds = sess.run(prediction, feed_dict={X: X_batch, Y: Y_batch})
correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(Y_batch, 1))
accuracy = tf.reduce_sum(tf.cast(correct_preds, tf.float32))
total_correct_preds += sess.run(accuracy)
print "Accuracy {0}".format(total_correct_preds/MNIST.test.num_examples)
允许用户指定上一层的输出节点的个数作为 input_size,本层的节点个数作为 output_size,并指定激活函数 activation_function 可以看到我们调用的时候位神经网络添加了两个 隐藏层 和 输出层
for l in range(1, layer_count): # layer [1,layer_count-1] is hidden layer
layer_iter = add_layer(layer_iter, layer_dims[l-1], layer_dims[l], activation_function=tf.nn.relu)
prediction = add_layer(layer_iter, layer_dims[layer_count-1], layer_dims[layer_count], activation_function=None)
entropy = tf.nn.softmax_cross_entropy_with_logits(labels=Y, logits=prediction)
loss = tf.reduce_mean(entropy)
注意这一行,我们配置了一个深度的神经网络,它包含两个隐藏层,一个输入层和一个输出层 隐藏层的节点数为 500
layer_dims = [784, 500, 500, 10]
python deep_neural_networks.py
运行过程中,如果出现网络错误,请重试。
运行输出:
Loss of epochs[5]: 19.5915279388
Loss of epochs[15]: 7.20698690414
...
Loss of epochs[65]: 0.24952724576
Accuracy 0.939
可以看到经过 70 轮的训练,准确度大约在 94%左右
你可以通过修改下面的这个代码片段来修改整个神经网络。
deep_neural_networks.py
layer_dims = [784, 500, 500, 10]
比如你可以去掉一层隐藏层
,并将隐藏层的节点数改为 600
deep_neural_networks.py
layer_dims = [784, 600, 10]
训练完的结果大概是这样:
Loss of epochs[5]: 13.1280488968
Loss of epochs[15]: 9.14239501953
Loss of epochs[25]: 3.60039186478
...
Loss of epochs[65]: 3.32054066658
Accuracy 0.9161
准确度大概 92%
的样子。have fun!