zoukankan      html  css  js  c++  java
  • mnist卷积网络实现

    • 加载MNIST数据
    from tensorflow.examples.tutorials.mnist import input_data
    mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
    
    • 运行TensorFlow的InteractiveSession
    import tensorflow as tf
    sess = tf.InteractiveSession()
    

    如果你没有使用 InteractiveSession ,那么你需要在启动session之前构建整个计算图,然后启动该计算图。

    • 构建一个多层卷积网络

    占位符

    我们通过为输入图像和目标输出类别创建节点,来开始构建计算图。

    x = tf.placeholder("float", shape=[None, 784])
    y_ = tf.placeholder("float", shape=[None, 10])
    

    输入图片 x 是一个2维的浮点数张量。这里,分配给它的 shape 为 [None, 784] ,其中 784 是一张展平的MNIST图片的维度。 None 表示其值大小不定,在这里作为第一个维度值,用以指代batch的大小,意即 x 的数量不定。输出类别值 y_ 也是一个2维张量,其中每一行为一个10维的one-hot向量,用于代表对应某一MNIST图片的类别。

    变量

    我们现在为模型定义权重 W 和偏置 b 。可以将它们当作额外的输入量,但是TensorFlow有一个更好的处理方式: 变量 。一个 变量 代表着TensorFlow计算图中的一个值,能够在计算过程中使用,甚至进行修改。在机器学习的应用过程中,模型参数一般用 Variable 来表示。

    W = tf.Variable(tf.zeros([784,10]))
    b = tf.Variable(tf.zeros([10]))
    

    我们在调用 tf.Variable 的时候传入初始值。在这个例子里,我们把 W 和 b 都初始化为零向量。 W 是一个784x10的矩阵(因为我们有784个特征和10个输出值)。 b 是一个10维的向量(因为我们有10个分类)。

    权重初始化

    为了创建这个模型,我们需要创建大量的权重和偏置项。这个模型中的权重在初始化时应该加入少量的噪声来打破对称性以及避免0梯度。由于我们使用的是ReLU神经元,因此比较好的做法是用一个较小的正数来初始化偏置项,以避免神经元节点输出恒为0的问题(dead neurons)。为了不在建立模型的时候反复做初始化操作,我们定义两个函数用于初始化。

    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)
    

    卷积和池化

    我们的卷积使用1步长(stride size),0边距(padding size)的模板,保证输出和输入是同一个大小。我们的池化用简单传统的2x2大小的模板做max pooling。为了代码更简洁,我们把这部分抽象成一个函数。

    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')
    

    第一层卷积

    现在我们可以开始实现第一层了。它由一个卷积接一个max pooling完成。卷积在每个5x5的patch中算出32个特征。卷积的权重张量形状是 [5, 5, 1, 32] ,前两个维度是patch的大小,接着是输入的通道数目,最后是输出的通道数目。 而对于每一个输出通道都有一个对应的偏置量。

    W_conv1 = weight_variable([5, 5, 1, 32])
    b_conv1 = bias_variable([32])
    

    为了用这一层,我们把 x 变成一个4d向量,其第2、第3维对应图片的宽、高,最后一维代表图片的颜色通道数(因为是灰度图所以这里的通道数为1,如果是rgb彩色图,则为3)。

    x_image = tf.reshape(x, [-1,28,28,1])
    

    我们把 x_image 和权值向量进行卷积,加上偏置项,然后应用ReLU激活函数,最后进行max pooling。

    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
    h_pool1 = max_pool_2x2(h_conv1)
    

    第二层卷积

    为了构建一个更深的网络,我们会把几个类似的层堆叠起来。第二层中,每个5x5的patch会得到64个特征。

    W_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)
    

    密集连接层

    现在,图片尺寸减小到7x7,我们加入一个有1024个神经元的全连接层,用于处理整个图片。我们把池化层输出的张量reshape成一些向量,乘上权重矩阵,加上偏置,然后对其使用ReLU。

    W_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

    为了减少过拟合,我们在输出层之前加入dropout。我们用一个 placeholder 来代表一个神经元的输出在dropout中保持不变的概率。这样我们可以在训练过程中启用dropout,在测试过程中关闭dropout。 TensorFlow的 tf.nn.dropout 操作除了可以屏蔽神经元的输出外,还会自动处理神经元输出值的scale。所以用dropout的时候可以不用考虑scale。

    keep_prob = tf.placeholder("float")
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
    

    输出层

    最后,我们添加一个softmax层,就像前面的单层softmax regression一样。

    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)
    

    训练和评估模型

    这个模型的效果如何呢?

    为了进行训练和评估,我们使用与之前简单的单层SoftMax神经网络模型几乎相同的一套代码,只是我们会用更加复杂的ADAM优化器来做梯度最速下降,在 feed_dict 中加入额外的参数 keep_prob 来控制dropout比例。然后每100次迭代输出一次日志。

    cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
    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, "float"))
    sess.run(tf.initialize_all_variables())
    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})
    print "test accuracy %g"%accuracy.eval(feed_dict={
    x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})
    

    以上代码,在最终测试集上的准确率大概是99.2%。

    • 完整运行代码和注释
    • import tensorflow as tf
      # 导入input_data用于自动下载和安装mNIST数据集
      from tensorflow.examples.tutorials.mnist import input_data

      mnist = input_data.read_data_sets('G:MNIST DATABASEMNIST_data',one_hot=True)
      # 创建一个交互式Session
      sess = tf.InteractiveSession()
      #创建两个占位符,x为输入网络的图像,y_为输入网络的图像类别
      x = tf.placeholder(tf.float32,shape=[None,784])
      y_ = tf.placeholder(tf.float32,shape=[None,10])
      #把二维的x(shape为[batch,784])变为4d的x_image,x_image的shape应该是[batch,28,28,1]
      #-1表示自动推测这个维度的size
      x_image = tf.reshape(x,[-1,28,28,1])
      keep_pro = tf.placeholder(tf.float32)

      def weight_variable(shape):
      return tf.Variable(tf.truncated_normal(shape,stddev=0.1))
      def biases_variable(shape):
      return tf.Variable(tf.constant(0.1,shape=shape))

      def conv2d_basic(x,W_shape,b_shape,name):
      Weights = tf.Variable(tf.truncated_normal(W_shape,stddev=0.1),name = 'W_'+ name)
      biases = tf.Variable(tf.constant(0.1,shape=b_shape),name= 'b_' + name)
      return tf.nn.relu(tf.nn.conv2d(x,Weights,strides=[1,1,1,1],padding="SAME") + biases)

      def max_pool_2x2(x):
      return tf.nn.max_pool(x,ksize=[1,2,2,1],
      strides=[1,2,2,1],padding="SAME")

      #第一层,卷积层,卷积核W=[5,5,1,32]表示卷积核尺寸5*5,输入通道1,输出通道32
      h_conv1 = conv2d_basic(x_image,[5,5,1,32],[32],name="conv1")
      h_pool1 = max_pool_2x2(h_conv1)

      # 第二层,卷积层
      h_conv2 = conv2d_basic(h_pool1,[5,5,32,64],[64],name="conv2")
      h_pool2 = max_pool_2x2(h_conv2)


      # 第三层,全连接层
      h_pool2_flat = tf.reshape(h_pool2,[-1,7*7*64])
      W_fc1 = weight_variable([7*7*64,1024])
      b_fc1 = weight_variable([1024])
      h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1)+b_fc1)

      # Dropout层
      h_fc1_drop = tf.nn.dropout(h_fc1,keep_pro)

      #输出层
      W_fc2 = weight_variable([1024,10])
      b_fc2 = weight_variable([10])

      prediction = tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2) + b_fc2)
      #预测值和真实值之间的交叉墒,train op, 使用ADAM优化器来做梯度下降。学习率为0.0001
      cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(prediction),reduction_indices=[1]))
      train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

      #评估模型,tf.argmax能给出某个tensor对象在某一维上数据最大值的索引。因为标签是由0,1组成了one-hot vector,返回的索引就是数值为1的位置
      correct_predict = tf.equal(tf.argmax(prediction,1),tf.argmax(y_,1))
      #计算正确预测项的比例,因为tf.equal返回的是布尔值,
      #使用tf.cast把布尔值转换成浮点数,然后用tf.reduce_mean求平均值
      accuracy = tf.reduce_mean(tf.cast(correct_predict,tf.float32))

      sess.run(tf.global_variables_initializer())

      for i in range(1000):
      batch = mnist.train.next_batch(50)
      if i%100==0:
      train_accuracy = accuracy.eval(feed_dict={x:batch[0],y_:batch[1],keep_pro:1.0})
      print("step %d,training accuracy %g,loss is %g" %(i,train_accuracy,cross_entropy.eval(feed_dict={x:batch[0],y_:batch[1],keep_pro:1.0})))
      train_step.run(feed_dict={x:batch[0],y_:batch[1],keep_pro:0.5})

      test_accuracy = accuracy.eval(feed_dict={x:mnist.test.images,y_:mnist.test.labels,keep_pro:1.0})
      print("test accuracy %g" %test_accuracy)
  • 相关阅读:
    linux删除目录的命令
    Windows XP下git通过代理下载android代码
    白话算法希尔排序
    操作系统——存储技术
    如何理解Linus Torvalds的“什么才是优秀程序员”的话
    程序员自我修养读书随笔——目标文件
    面试求职:大数据处理总结
    持久化与Session定义
    java中byte转换int时为何与0xff进行与运算
    OSI七层相关协议
  • 原文地址:https://www.cnblogs.com/qqw-1995/p/9739159.html
Copyright © 2011-2022 走看看