CNN实战:tensorflow训练mnist手写数字识别

用tensorflow可以轻松的搭建卷积神经网络,layer层api的加入更是方便了整个过程。本文以mnist手写数字识别的训练为例,轻松挑战99%准确率。

准备

首先,导入必要的库和函数。

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

载入mnist数据,注意这里input_data.read_data_sets的参数reshape=Fales,以保留3维的图片数据,否则图片会被变换为向量。由于是黑白图片,所以这里的颜色通道数为1。这里image的shape为(None,28,28,1)。

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True, reshape=False)

定义数据流图结构

定义变量。这里我们不需要再定义各层网络的权重和偏差,这便是layers的方便之处,它们会被自动创建。

x = tf.placeholder(tf.float32, shape=(None,28,28,1))
y_ = tf.placeholder(tf.float32, shape=(None,10))
istrain = tf.placeholder(tf.bool) # dropout时参数用到

然后开始定义卷积网络结构,激活函数采用relu,这里使用卷积层⇒池化层⇒卷积层⇒池化层。 继续阅读“CNN实战:tensorflow训练mnist手写数字识别”

用tensorflow解码图片

用深度学习进行图片识别时,往往需要将各原始图片转换为相同的尺寸,并且数字化。其实,tensorflow本身就能非常方便地实现这个过程。

import tensorflow as tf

"""读取图片文件"""
file1 = tf.read_file('image.jpg')

"""解码图片,png格式用tf.image.decode_png,
channels=3表示RGB,1表示灰度"""
image = tf.image.decode_jpeg(file1, channels=3)

"""调整图片大小,size=[new_height, new_width]"""
image = tf.image.resize_images(image, size=[32,32])

"""转化图片转化为float32类型,并缩放到[0,1]之间,
也可使用 tf.cast(image, tf.float32)/255(一般图片类型最大值为255)"""
image = tf.image.convert_image_dtype(image, tf.float32)

# 在会话中运行
sess = tf.Session()
sess.run(image)

tensorflow实现mnist手写数字识别

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

# 载入数据
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

# 定义tensorflow结构
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y_ = tf.placeholder(tf.float32, [None, 10])

"""激励函数softmax和loss函数交叉熵"""
y = tf.nn.softmax(tf.matmul(x, W) + b)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), axis=1))

"""或者用tf内置的loss函数,注意tf.nn.softmax_cross_entropy_with_logits已内置softmax变换"""
# y_l = tf.matmul(x,W) + b
# cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_l))

"""用梯度下降提升"""
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

"""初始化全部变量"""
init = tf.global_variables_initializer()

# 训练
sess = tf.Session()
sess.run(init)

"""进行600次更新,SGD每批次输入100个样本"""
for i in range(600):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
# 评估模型,每20步打印准确率
if i % 20 == 0:
"""tf.argmax返回最大值的index,tf.equal比较是否相等"""
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
"""转换为数字并求平均,如[True,False,False,True]转化为[1,0,0,1],平均值为0.5"""
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
"""用测试数据计算,并打印准确率"""
print(i, sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

sess.close()

tensorflow的GPU配置

以Ubuntu系统为例:

1、首先安装Cuda Toolkit
下载地址:https://developer.nvidia.com/cuda-downloads
安装步骤:

# Install repository meta-data:
sudo dpkg -i cuda-repo-<distro>_<version>_<architecture>.deb
# Update the Apt repository cache:
sudo apt-get update
# Install CUDA:
sudo apt-get install cuda

2、安装cuDNN
下载地址:https://developer.nvidia.com/cudnn
配置步骤(假设Cuda toolkit安装在/usr/local/cuda):

tar xvzf cudnn-8.0-linux-x64-v5.1-ga.tgz
sudo cp -P cuda/include/cudnn.h /usr/local/cuda/include
sudo cp -P cuda/lib64/libcudnn* /usr/local/cuda/lib64
sudo chmod a+r /usr/local/cuda/include/cudnn.h /usr/local/cuda/lib64/libcudnn*

3、安装其他依赖

sudo apt-get install libcupti-dev

4、安装支持gpu版本的tensorflow

pip install tensorflow-gpu