smile学子吧 关注:8贴子:998
  • 8回复贴,共1

TensorFlow:CNNs卷积神经网络:Mnist手写数字识别

只看楼主收藏回复



IP属地:广东1楼2018-05-31 09:19回复
    # coding=gbk
    '''
    Created on 2018年6月6日
    @author: lenovo
    '''
    import tensorflow as tf
    # 获取数据(如果存在就读取,不存在就下载完再读取)
    from tensorflow.examples.tutorials.mnist import input_data
    mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)


    IP属地:广东2楼2018-06-06 16:37
    回复
      2025-05-15 17:57:35
      广告

      #初始化权重函数
      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')
      #定义一个2*2的最大池化层
      def max_pool_2_2(x):
      return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')


      IP属地:广东3楼2018-06-06 16:37
      回复

        if __name__ == "__main__":
        #输入与输出
        x = tf.placeholder("float", shape = [None, 784])#输入占位符(每张手写数字28*28个像素点)
        y_ = tf.placeholder("float", shape = [None, 10])#输入占位符(这张手写数字具体代表的值,0-9对应矩阵的10个位置)
        #初始化权重,第一层卷积,32的意思代表的是输出32个通道
        # 其实,也就是设置32个卷积,每一个卷积都会对图像进行卷积操作
        w_conv1 = weight_variable([5,5,1,32])
        #初始化偏置项
        b_conv1 = bias_variable([32])
        #将输入的x转成一个4D向量,第2、3维对应图片的宽高,最后一维代表图片的颜色通道数
        # 输入的图像为灰度图,所以通道数为1,如果是RGB图,通道数为3
        # tf.reshape(x,[-1,28,28,1])的意思是将x自动转换成28*28*1的数组
        # -1的意思是代表不知道x的shape,它会按照后面的设置进行转换
        x_image = tf.reshape(x,[-1,28,28,1])
        # 卷积并激活
        h_conv1 = tf.nn.relu(conv2d(x_image,w_conv1) + b_conv1)
        #池化
        h_pool1 = max_pool_2_2(h_conv1)
        #第二层卷积
        #初始权重
        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_2_2(h_conv2)
        # 设置全连接层的权重
        w_fc1 = weight_variable([7*7*64,1024])
        # 设置全连接层的偏置
        b_fc1 = bias_variable([1024])
        # 将第二层卷积池化后的结果,转成一个7*7*64的数组
        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("float")
        h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)
        #第二个全连接层
        w_fc2 = weight_variable([1024,10])
        b_fc2 = bias_variable([10])
        #最后一层输出
        y = tf.matmul(h_fc1_drop,w_fc2) + b_fc2
        #网络迭代,交叉熵损失
        crossEntropyLoss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y_, logits = y))
        trainStep = tf.train.AdamOptimizer().minimize(crossEntropyLoss)
        correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
        accuracy = tf.reduce_mean(tf.cast(correct_prediction,"float"))
        # 初始化变量
        init = tf.global_variables_initializer()
        sess = tf.Session()
        sess.run(init)


        IP属地:广东4楼2018-06-06 16:37
        回复
          batchSize = 50
          for i in range(1000):
          batch = mnist.train.next_batch(batchSize)
          trainStep.run(session = sess,feed_dict={x:batch[0],y_:batch[1],keep_prob:0.5})
          if i%100 == 0:
          trainAccuracy = accuracy.eval(session=sess,feed_dict={x:batch[0],y_:batch[1],keep_prob:0.5})
          print("step %d,training accuracy %g"%(i,trainAccuracy))
          print("test accuracy %g" % accuracy.eval(session=sess,feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))


          IP属地:广东5楼2018-06-06 16:38
          回复
            实验结果:
            Extracting MNIST_data/train-images-idx3-ubyte.gz
            Extracting MNIST_data/train-labels-idx1-ubyte.gz
            Extracting MNIST_data/t10k-images-idx3-ubyte.gz
            Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
            2018-06-06 16:25:31.827200: I C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\36\tensorflow\core\platform\cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
            step 0,training accuracy 0.12
            step 100,training accuracy 0.86
            step 200,training accuracy 0.96
            step 300,training accuracy 0.92
            step 400,training accuracy 0.92
            step 500,training accuracy 0.96
            step 600,training accuracy 0.98
            step 700,training accuracy 0.96
            step 800,training accuracy 0.92
            step 900,training accuracy 1
            test accuracy 0.9844


            IP属地:广东6楼2018-06-06 16:38
            回复
              谢谢大佬


              来自iPhone客户端7楼2018-09-25 16:31
              收起回复