02 CNN手写数字识别

cnn:
进行卷积运算(首先许定义权重w和偏移b)

#cnn : 1 卷积
# ABC 
# A: 激励函数+矩阵 乘法加法
# A CNN :  pool(激励函数+矩阵 卷积 加法)
# C:激励函数+矩阵 乘法加法(A-》B)
# C:激励函数+矩阵 乘法加法(A-》B) + softmax(矩阵 乘法加法)
# loss:tf.reduce_mean(tf.square(y-layer2))
# loss:code
#1 import 
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
# 2 load data
mnist = input_data.read_data_sets('MNIST_data',one_hot = True)

# 3 input  输入数据
imageInput = tf.placeholder(tf.float32,[None,784]) # 28*28 
labeInput = tf.placeholder(tf.float32,[None,10]) # knn

# 4 data reshape  数据维度的调整
# [None,784]->M*28*28*1  2D->4D  28*28 wh 1 channel 
#将2维[None,784] 调整为4维 M*28*28*1 (28*28表示图片宽高;1表示读取灰度图像,1为灰色通道;经过转换后的剩余的元素共同构成M) 
imageInputReshape = tf.reshape(imageInput,[-1,28,28,1])

# 5 卷积 w0 : 卷积内核 5*5 out:32  in:1 
w0 = tf.Variable(tf.truncated_normal([5,5,1,32],stddev = 0.1))#服从正态分布的数据([最终生产数据的维度],期望方差)卷积运算的内核大小5*5,输入维度1,可认为是上面那1个灰色通道,32表明是32维度
b0 = tf.Variable(tf.constant(0.1,shape=[32]))  #定义一个常量,其维度为32

# 6 # layer1:激励函数+卷积运算 conv2d (输入输出很难保证线性,所以采用激励函数,保证非线性)
# imageInputReshape : M*28*28*1  w0: 5,5,1,32  
#tf.nn.conv2d(输入图像数据,权重矩阵,每次移动的步长,'SAME'表示卷积核可以停留在图像边缘)
#relu : 激励函数
layer1 = tf.nn.relu(tf.nn.conv2d(imageInputReshape,w0,strides=[1,1,1,1],padding='SAME')+b0)
#layer1的大小: M*28*28*32

# (考虑数据太大,添加池化层)pool是完成下采样 数据量减少很多:  M*28*28*32 --> M*7*7*32 这些数表示维度(ksize=[1,4,4,1],那么:M/1=1,28/4=7,28/4=7,32/1=32)
#tf.nn.max_pool(池化数据,池化缩小程度,池化层步长,'SAME'能够停留在池化层边缘)
layer1_pool = tf.nn.max_pool(layer1,ksize=[1,4,4,1],strides=[1,4,4,1],padding='SAME')
# [1 2 3 4]->[4]  (max_pool表示: 例如将4维[1 2 3 4]池化成1维,一维的数据;来源于最大值,则池化后为[4])

#以下开始实现输出层
# 7 layer2 out : 激励函数+乘加运算:  softmax(激励函数 + 乘加运算)
#softmax为回归函数,用来计算输出值
# [7*7*32,1024]    tf.truncated_normal([数据维度],方差=0.1)
w1 = tf.Variable(tf.truncated_normal([7*7*32,1024],stddev=0.1))
b1 = tf.Variable(tf.constant(0.1,shape=[1024]))
#维度转换
h_reshape = tf.reshape(layer1_pool,[-1,7*7*32])# M*7*7*32 -> N*N1(将4维转换为2维)
# [N*7*7*32] * [7*7*32,1024] = N*1024 (进行矩阵相乘)
h1 = tf.nn.relu(tf.matmul(h_reshape,w1)+b1) #激励函数+乘加运算matmul


# 7.1 softMax   tf.truncated_normal([数据维度],方差 = 0.1)
w2 = tf.Variable(tf.truncated_normal([1024,10],stddev=0.1))
b2 = tf.Variable(tf.constant(0.1,shape=[10]))
pred = tf.nn.softmax(tf.matmul(h1,w2)+b2)# N*1024  1024*10 = N*10
# N*10( 概率 )N1【0.1 0.2 0.4 0.1 0.2 。。。】  N表示n张图片,10表示预测在0-9分布的概率
# label。        【0 0 0 0 1 0 0 0.。。】
loss0 = labeInput*tf.log(pred)#对结果进行压缩,得到唯一的标识1,但此时任然是10维的数据,需要累加成1维
loss1 = 0
# 7.2 
for m in range(0,500):#  test 500,进行测试时,每次给500张,
    for n in range(0,10):    #将10个维度的数据进行累加
        loss1 = loss1 - loss0[m,n]  #这里得到的是正数,在使用梯度下降法时,要变成-号
loss = loss1/500  #除以500组数据

# 8 train 开始训练,采用梯度下降,每次下降0.01.尽可能缩小当前的loss
train = tf.train.GradientDescentOptimizer(0.01).minimize(loss)

# 9 run
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(100):
        images,labels = mnist.train.next_batch(500)
        sess.run(train,feed_dict={imageInput:images,labeInput:labels})
        
        pred_test = sess.run(pred,feed_dict={imageInput:mnist.test.images,labeInput:labels})
        acc = tf.equal(tf.arg_max(pred_test,1),tf.arg_max(mnist.test.labels,1))
        acc_float = tf.reduce_mean(tf.cast(acc,tf.float32))
        acc_result = sess.run(acc_float,feed_dict={imageInput:mnist.test.images,labeInput:mnist.test.labels})
        print(acc_result)
        


你可能感兴趣的:(02 CNN手写数字识别)