zoukankan      html  css  js  c++  java
  • 实现CNN卷积神经网络

    以上是模型,下面是代码:

      1 import tensorflow as tf
      2 import numpy as np
      3 import time
      4 from tensorflow.examples.tutorials.mnist import input_data
      5 
      6 import os
      7 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
      8 
      9 start = time.clock()
     10 
     11 # 下载并载入MNIST 手写数字库
     12 mnist = input_data.read_data_sets("./data/MNIST", one_hot=True)
     13 
     14 input_x = tf.placeholder(tf.float32, shape=[None, 28 * 28]) / 255  # 灰度的处理
     15 output_y = tf.placeholder(tf.float32, shape=[None, 10])   #输出10个数字的标签
     16 input_x_images = tf.reshape(input_x, shape=[-1, 28, 28, 1])  #改变形状之后的输入
     17 
     18 # 从Test(测试)数据集里选取3000个手写数字的图片和对应的标签
     19 test_x = mnist.test.images[:3000]
     20 test_y = mnist.test.labels[:3000]
     21 
     22 # 构建我们的卷积神经网络
     23 # 第一层卷积
     24 conv1 = tf.layers.conv2d(inputs=input_x_images,  # 形状为[28,28,1]
     25                          filters=32,  # 32个过滤器,输出的深度位32
     26                          kernel_size=[5, 5],  # 过滤器在二维的大小是(5*5)
     27                          strides=1,  # 步长是1
     28                          padding="same",  # snme表示输出大小不变,因此要在外围补零2圈
     29                          activation=tf.nn.relu  # 表示激活函数是relu
     30                          )  # 形状[28,28,32]
     31 
     32 # 第一层池化(亚采样)
     33 pool1 = tf.layers.max_pooling2d(
     34     inputs=conv1,  # 形状[28,28,32]
     35     pool_size=[2, 2],  # 过滤器在二维的大小是[2,2]
     36     strides=2  # 步长是2
     37 )  # 形状[14,14,32]
     38 
     39 # 第二层卷积
     40 conv2 = tf.layers.conv2d(inputs=pool1,  # 形状为[14,14,32]
     41                          filters=64,  # 64个过滤器,输出的深度位64
     42                          kernel_size=[5, 5],  # 过滤器在二维的大小是(5*5)
     43                          strides=1,  # 步长是1
     44                          padding="same",  # snme表示输出大小不变,因此要在外围补零2圈
     45                          activation=tf.nn.relu  # 表示激活函数是relu
     46                          )  # 形状[14,14,64]
     47 
     48 # 第二层池化(亚采样)
     49 pool2 = tf.layers.max_pooling2d(
     50     inputs=conv2,  # 形状[14,14,64]
     51     pool_size=[2, 2],  # 过滤器在二维的大小是[2,2]
     52     strides=2  # 步长是2
     53 )  # 形状[7,7,64]
     54 
     55 #平坦化(flat)
     56 flat = tf.reshape(pool2,shape=[-1,7 * 7 * 64])  #形状[7 * 7 * 64]
     57 
     58 #1024个神经元的全连接层
     59 dense = tf.layers.dense(inputs=flat,units=1024,activation=tf.nn.relu)
     60 
     61 #Dropout :丢弃 50%  rate = 0.5
     62 dropout = tf.layers.dropout(inputs=dense,rate=0.5)
     63 
     64 #10个神经元的全连接层,这里不用激活函数来做非线性化了。
     65 logits = tf.layers.dense(inputs=dropout,units=10)  #输出形状[1,1,10]
     66 
     67 #计算误差(计算 Cross entropy(交叉熵)),再用softmax计算百分比概率
     68 loss = tf.losses.softmax_cross_entropy(onehot_labels=output_y,logits=logits)
     69 
     70 # Adam 优化器来最小化误差,学习率0.001
     71 train_op = tf.train.AdadeltaOptimizer(learning_rate=0.001).minimize(loss)
     72 
     73 #精度,计算,预测值 和 实际标签 的匹配程度
     74 #返回 (accuracy .update_op) 会创建两个局部变量
     75 accuracy = tf.metrics.accuracy(
     76     labels=tf.argmax(input=output_y,axis=1),
     77     predictions=tf.argmax(input=logits,axis=1)
     78 )[1]
     79 
     80 #创建会话
     81 with tf.Session() as sess:
     82     #初始化变量
     83     init = tf.group(tf.global_variables_initializer(),tf.local_variables_initializer())
     84     sess.run(init)
     85     for i in range(20000):
     86         batch = mnist.train.next_batch(50) #从Train(训练)数据集里下一个50个样本
     87         train_loss,train_op_ = sess.run([loss,train_op],feed_dict={input_x:batch[0],output_y:batch[1]})
     88         if i % 100 == 0:
     89             test_accuracy = sess.run(accuracy,feed_dict={input_x:test_x,output_y:test_y})
     90             print(("Step+%d,Train loss=%.4f,[Test accuracy=%.2f]") % (i,train_loss,test_accuracy))
     91 
     92     #测试:打印20个 预测值 和 真实值 的对
     93     test_output = sess.run(logits,feed_dict={input_x:test_x[:20]})
     94     inference_y = np.argmax(test_output,1)
     95     print(inference_y," Inference number") #推测的数字
     96     print(np.argmax(test_y[:20],1),"Real numbers") #真实的数字
     97 
     98     #显示时间
     99     end = time.clock()
    100     print(end - start, "")

    当然CNN还有很长一段路要走。代码不容易,且敲且珍惜。

  • 相关阅读:
    一个空类会生成哪些默认函数
    What is VMR(Video Mixing Render)From MSDN
    DirectX backface culling(背面剔除)
    D3DPOOL(资源池)
    两道概率题供大家周末把玩
    空间两点间的距离
    n != n, n == n
    C++默认参数
    D3DPT_TRIANGLELIST与D3DPT_TRIANGLESTRIP
    D3D中的设备丢失
  • 原文地址:https://www.cnblogs.com/tianqianlan/p/10699172.html
Copyright © 2011-2022 走看看