Tensorflow学习——MNIST多层卷积网络解决方案

Tensorflow官方文档中文版学习纪要


上篇MNIST的正确率只有91%,本篇文章用卷积神经网络来改善效果。准确率预计99.2%;

参考:http://blog.csdn.net/smf0504/article/details/56666229

  1. # coding=utf-8  
  2.   
  3. import tensorflow as tf  
  4.   
  5. # import data  
  6. from tensorflow.exaemples.tutorials.mnist import input_data  
  7. mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)  
  8.   
  9. # 卷积神经网络会有很多的权重和偏置需要创建  
  10. # 定义初始化函数以便重复使用  
  11. def weigth_variable(shape):  
  12.     # 给权重制造一些随机的噪声来打破完全对称以及避免0梯度,由于我们使用的是ReLU神经元,因此比较好的做法是用一个较小的正数来初始化偏置
        # 项,以避免神经元节点输出恒为0的问题(dead neurons)例如这里截断的正态分布,标准差为0.1
      
  13.     inital = tf.truncated_normal(shape, stddev=0.1)  
  14.     return tf.Variable(inital)  
  15.   
  16. def bias_variable(shape):  
  17.     # 由于使用Relu,也给偏置增加一些小的正值(0.1)用来避免死亡节点(dead neurous)  
  18.     inital = tf.constant(0.1, tf.float32, shape)  
  19.     return tf.Variable(inital)  
  20.   
  21. # 卷积层和池化层也是接下来重复使用的  
  22. # 定义卷积层和池化层  
  23. def conv2d(x, W):  
  24.     return tf.nn.conv2d(x, W, strides=[1111], padding='SAME') #卷积使用步长1,0边距模板,保证输入与输出同大小
  25.   
  26. def max_pool_2X2(x):  
  27.     return tf.nn.max_pool(x, ksize=[1221], strides=[1221], padding='SAME') #用2X2大小模板做max pooling
  28.   
  29. # 在正式设计卷积神经网络之前,先定义输入placeholder,x是特征,y是真实的label  
  30. x = tf.placeholder(tf.float32, [None784])  
  31. y = tf.placeholder(tf.float32, [None10])  
  32. x_image = tf.reshape(x, [-128281])  
  33.   
  34. # 定义第一个卷积层  
  35. # 先使用前面写好的函数进行参数初始化,包括weigth和bias,  
  36. # 接着使用conv2d函数进行卷积操作,并加上偏置,  
  37. # 然后再使用ReLu激活函数进行非线性处理,  
  38. # 最后,使用最大池化函数对卷积的输出结果进行池化操作  
  39. W_conv1 = weigth_variable([55132])  # patch 5x5, in size 1, out size 32  
  40. # 矩阵用大写字母开头,便于自己下面区分(这只是个人建议)  
  41. b_conv1 = bias_variable([32])  
  42. h_conv1 = tf.nn.relu(tf.conv2d(x_image, W_conv1) + b_conv1)  # output size 28x28x32  
  43. h_pool1 = tf.max_pool_2X2(h_conv1)  # output size 14x14x32  
  44.   
  45. # 定义第二层卷积层  
  46. # 步骤如上一层,只是参数有所改变而已  
  47. W_conv2 = weigth_variable([553264])  # patch 5x5, in size 32, out size 64  
  48. b_conv2 = bias_variable([64])  
  49. h_conv2 = tf.nn.relu(tf.conv2d(h_pool1, W_conv2) + b_conv2)  # output size 14x14x64  
  50. h_pool2 = tf.max_pool_2X2(h_conv2)   # output size 7x7x64  
  51.   
  52. # 全连接层  
  53. W_fc1 = weigth_variable([7*7*641024])  
  54. b_fc1 = bias_variable([1024])  
  55. # [n_samples, 7, 7, 64] ->> [n_samples, 7*7*64]  
  56. h_pool2_flat = tf.reshape(h_pool2, [-17*7*64])  
  57. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)  
  58.   
  59. # 为了减轻过拟合,增加一个dropout层  
  60. keep_prob = tf.placeholder(tf.float32)  
  61. h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)  
  62.   
  63. # 将dropout层的输出连接到一个softmax层,得到最后的概率输出  
  64. W_fc2 = weigth_variable([102410])  
  65. b_fc2 = bias_variable([10])  
  66. pre = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)  
  67.   
  68. # 最后定义损失函数为cross entropy,和之前一样,但是最后的优化器使用Adam,并给予一个比较小的学习率1e-4  
  69. cross_entropy = tf.reduce_mean(tf.reduce_sum(y*tf.log(pre), reduction_indices=[1]))  
  70. train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)  # 使用的优化方法,以及追求的目标  
  71.   
  72. # 定义评测准确率的操作  
  73. correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(pre, 1))  
  74. accuray = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))  
  75.   
  76. # train,开始训练  
  77. # 首先依然是初始化所有变量,设置训练是的Dropout的keep_prob比率为0.5,  
  78. # 然后使用大小为50的mini_batch,共进行20000次训练迭代,  
  79. # 参与训练的样本数量总共100万,其中每100次训练,会准确率进行一次评测时keep_prob为1,用以实时监测模型的性能  
  80. with tf.InteractiveSession() as sess:  
  81.     tf.global_variables_initializer().run()  
  82.     for i in range(20000):  
  83.         batch = mnist.train.next_batch(50)  
  84.         if i % 100 == 0:  
  85.             train_accuracy = accuray.eval(feed_dict={x: batch[0], y: batch[1], keep_prob: 1.0})  
  86.             print("step %d, training accuracy %g" % (i, train_accuracy))  
  87.         train_step.run(feed_dict={x: batch[0], y: batch[1], keep_prob: 0.5})  
  88.     # 全部训练完后,在最终的测试集上进行全面的测试,得到整体分类准确率  
  89.     print("test accuracy %g" % accuray.eval(feed_dict={x: mnist.test.images, y: mnist.test.labels, keep_prob: 1.0}))  




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值