Tensorflow学习总结(三)

一、学习内容

  • 卷积神经网络(CNN)内容、原理。
  • 用tensorflow搭建卷积神经网络(CNN)模型。
  • 利用CNN模型,解决MNIST手写识别问题,提高精度到99%以上。

二、白话卷积神经网络

我认为(拙见)以彩色图片识别为例:

  • 卷积核:CNN利用卷积核来对图片的局部特征进行提取,例如:彩色图片有黄、绿、蓝三个基本原色构成。那么,可以分别用黄、绿、蓝作为卷积核来分别对整张图片进行特征提取。那么提取到的三个平面就分别是这张图片的黄色、绿色、蓝色的部分特征。
    在这里插入图片描述
  • 卷积操作:卷积操作就是用卷积核和整体对应卷积核的部分做内积。
    在这里插入图片描述
  • 池化:对卷积操作后的特征最大化抽取
    在这里插入图片描述

三、tensorflow基于CNN实现手写数字(MNIST)识别改进

代码注释部分为解释(详细)
也可以点击课程视频连接:基于tensorflow实现CNN&MNIST手写数据识别视频教程

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('MNIST.data', one_hot=True)

#定义批次
batch_size = 100
#计算一共有多少次批次
n_batch = mnist.train.num_examples // batch_size


#初始化权值
def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1) #生成一个截断的正态分布
    return tf.Variable(initial)

#初始化偏值
def biases_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

#卷积层
def conv2d(x, w):

    #x input tensor of shape [batch, in_height, in_width, in_channel]
    #w filter / kernel tensor of shape [filter_height, filter_width, in_channels, out_channels]
    #strides[0] = strides[3] = 1, strides[1] 代表x方向的步长,stridesp[2]代表y方向的步长
    #padding: A string from:'SAME','VALID'

    return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')

#池化层
def max_pool_2x2(x):
    #ksize[1,x,y,1]
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

#定义连个placeholder

x = tf.placeholder(tf.float32, [None, 784])     #28*28
y = tf.placeholder(tf.float32, [None, 10])      #[0,1,..,10]

#改变x的格式转变为4D的向量tensor[batch, in_height, in_width, in_channels]
x_image = tf.reshape(x, [-1, 28, 28, 1])


#初始化第一个卷积层的权值和偏置值
w_conv1 = weight_variable([5, 5, 1, 32])   #用5*5的32个卷积核,从一个平面抽取特征, 得到32个面
b_conv1 = biases_variable([32])

#卷积后,加上偏值, 然后应用于relu激活函数
h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

#初始化第二个卷积层的权值和偏置值,再池化
w_conv2 = weight_variable([5, 5, 32, 64]) #用5*5的64个卷积核,从32个平面抽取特征,得到64个平面
b_conv2 = biases_variable([64])

#卷积后,加上偏值,然后应用于relu函数,再池化
h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

#28*28--> max_pooling --> 14*14 -->max_pooling --> 7*7
#得到64张7*7的平面

#初始化第一个全连接层
w_fc1 = weight_variable([7*7*64, 1024]) #上一层有7*7且64张, 全连接层有1024个神经元
b_fc1 = weight_variable([1024])

#把池化层2的输出扁平化
h_pool_flat = tf.reshape(h_pool2, [-1, 7*7*64])
#求第一个全连接层的输出
h_fc1 = tf.nn.relu(tf.matmul(h_pool_flat, w_fc1) + b_fc1)


#keep_dorp 用来标书神经元的输出概率
keep_drop = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_drop)

#初始化第二个全连接层
W_fc2 = weight_variable([1024, 10])
b_fc2 = biases_variable([10])

#计算输出
prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

#交叉熵
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction))
#优化
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
#结果储存在一个布尔列表中
correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
#求准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))


with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for epoch in range(21):
        for batch in range(n_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys, keep_drop: 0.7})

        acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y:mnist.test.labels, keep_drop: 1.0})
        print("Iter " + str(epoch) + ", Testing Accuracy= " + str(acc))





四、实验结果

由于每层神经元设置较多,在作者的垃圾电脑配置下,直接给电脑跑崩溃!这是在CentOS服务器(GPU)实验环境下跑的结果:
在这里插入图片描述


Tensorflow教程连接:Tensorflow教程

发布了15 篇原创文章 · 获赞 2 · 访问量 2195

猜你喜欢

转载自blog.csdn.net/Mr_WangYC/article/details/103270089