TensorFlow深度学习新手教程:TensorFlow实现简单的卷积网络

来源:互联网 发布:velocity定义数组 编辑:程序博客网 时间:2024/05/20 05:03

TensorFlow深度学习新手教程:TensorFlow实现简单的卷积网络


        TensorFlow是一个非常强大的用来做大规模数值计算的库。其所擅长的任务之一就是实现以及训练深度神经网络。本教程将讲解如何使用TensorFlow实现一个简单的卷积神经网络(CNN),使用的数据集为经典的MNIST数据集,预期可以达到99%左右的准确率。我相信,通过此案例,读者会更进一步的理解与掌握深度神经网络的设计要点。

        在本教程中,我们将学到构建一个TensorFlow模型的基本步骤,并将通过这些步骤为MNIST构建一个深度卷积神经网络。这个教程假设你已经熟悉神经网络的基础理论和MNIST数据集(MNIST数据集的官网是Yann LeCun's website)。

        在准备工作就绪后,我们就可以构建CNN。以下代码是结合本人对CNN理解并对现有代码整理而成,注释是根据本人理解添加的,如有错误请指正。

# -*- coding: utf-8 -*-import osos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'# 载入TensorFlow并加载MNIST数据集# 创建一个TensorFlow默认的InteractiveSessionfrom tensorflow.examples.tutorials.mnist import input_dataimport tensorflow as tfmnist = input_data.read_data_sets("MNIST_data/", one_hot=True)sess = tf.InteractiveSession()# 定义初始化函数,实现cnn权重和偏置的创建def weight_variable(shape):    initial = tf.truncated_normal(shape, stddev=0.1)    return tf.Variable(initial)def bias_variable(shape):    initial = tf.constant(0.1, shape=shape)    return tf.Variable(initial)# 定义创建函数:卷基层、池化层def conv2d(x, w):    return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')def max_pool_2x2(x):    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')# 定义输入的placeholderx = tf.placeholder(tf.float32, [None, 784])y_ = tf.placeholder(tf.float32, [None, 10])x_image = tf.reshape(x, [-1, 28, 28, 1])# 定义conv1w_conv1 = weight_variable([5, 5, 1, 32])b_conv1 = bias_variable([32])h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)h_pool1 = max_pool_2x2(h_conv1)# 定义conv2w_conv2 = weight_variable([5, 5, 32, 64])b_conv2 = bias_variable([64])h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2)h_pool2 = max_pool_2x2(h_conv2)# 对conv2的输出tensor进行变形转成1D向量,随后连接fc1w_fc1 = weight_variable([7*7*64, 1024])b_fc1 = bias_variable([1024])h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1) + b_fc1)# Dropout层,减轻过拟合keep_prob = tf.placeholder(tf.float32)h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)# Softmax层,连接到Dropout层输出w_fc2 = weight_variable([1024, 10])b_fc2 = bias_variable([10])y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, w_fc2) + b_fc2)# 定义损失函数cross entropycross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y_conv), reduction_indices=[1]))train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)# 定义评测准确率correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))# 训练tf.global_variables_initializer().run()for i in range(20000):    batch = mnist.train.next_batch(50)    if i % 100 == 0:        train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1],                                                  keep_prob: 1.0})        print("step %d, training accuracy %g" % (i, train_accuracy))    train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})# 在test上进行全面的测试,得到整体的分类准确率print("test accuracy %g" % accuracy.eval({x: mnist.test.images, y_: mnist.test.labels,                                          keep_prob: 1.0}))

        到此,我们就完成TensorFlow构建简单卷积网络的工作,获得准确率为99%左右,基本可以满足手写数字识别准确率的要求。

       在后续工作中,我将继续为大家展现TensorFlow带来的无尽乐趣,我将和大家一起探讨深度学习的奥秘。当然,如果你感兴趣,我的Weibo将与你一起分享最前沿的人工智能、机器学习、深度学习与计算机视觉方面的技术。


阅读全文
0 0
原创粉丝点击