码迷,mamicode.com
首页 > 其他好文 > 详细

Tensorflow快速入门2--实现手写数字识别

时间:2017-01-16 17:01:10      阅读:948      评论:0      收藏:1      [点我收藏+]

标签:add   markdown   nis   equal   nes   梯度下降   分类   sam   索引   

Tensorflow快速入门2–实现手写数字识别

环境: 虚拟机ubuntun16.0.4 Tensorflow(仅使用cpu版)
Tensorflow安装见:
http://blog.csdn.net/yhhyhhyhhyhh/article/details/54429034
或者:
http://www.tensorfly.cn/tfdoc/get_started/os_setup.html

本文将利用Tensorflow以softmax回归和卷积神经网络两种模型简单测试MNIST数据集,快速实现手写数字识别的测试。仅Tensorflow作为练习,不讲解过多模型、框架等理论知识。

目录

1.MNIST数据集

2.softmax回归测试MNIST

3.卷积神经网络测试MNIST

4.Tensorflow学习文档

1.MNIST数据集

MNIST数据集的官网:http://yann.lecun.com/exdb/mnist/
按照TensorFlow中文社区教程的方法将MNIST数据训练数据和测试数据加载到自己的代码中。
1)下载MNIST数据集
input_data.py文件下载:input_data.py
在终端中运行:python ~/Test/input_data.py
(我的数据集和input_data.py文件放在了主目录下的Test文件夹下,注意路径。)
2)加载到代码中
在用到MNIST数据的python代码中加入以下:

#导入MNIST数据
import input_data
mnist = input_data.read_data_sets(‘MNIST_data/‘, one_hot=True)

每一个MNIST数据单元有两部分组成(训练数据集和测试数据集都是):一张包含手写数字的图片和一个对应的标签。
因此,在MNIST训练数据集中,mnist.train.images 是一个形状为 [60000, 784] 的张量,第一个维度数字用来索引图片,第二个维度数字用来索引每张图片中的像素点。在此张量里的每一个元素,都表示某张图片里的某个像素的强度值,值介于0和1之间。

技术分享

相对应的MNIST数据集的标签是介于0到9的数字,用来描述给定图片里表示的数字。为了用于这个教程,我们使标签数据是”one-hot vectors”。 一个one-hot向量除了某一位的数字是1以外其余各维度数字都是0。所以在此教程中,数字n将表示成一个只有在第n维度(从0开始)数字为1的10维向量。比如,标签0将表示成([1,0,0,0,0,0,0,0,0,0,0])。因此, mnist.train.labels 是一个 [60000, 10] 的数字矩阵。

技术分享

2.softmax回归测试MNIST

1)softmax回归模型
点击查看softmax回归详细讲解的一个帖子:

简单来说,softmax回归是logistic回归对多分类问题的推广,当是两分类时,就是logistic回归。softmax回归更适合类别间是互斥的,比如字符识别等。Softmax代价函数与logistic 代价函数在形式上非常类似,只是在Softmax损失函数中对类标记的 个可能值进行了累加。

2)简单测试MNIST
注意路径。

yhh@ubuntu:~/Test$ python input_data.py
yhh@ubuntu:~/Test$ python softmax_tf_mnist.py

softmax回归测试MNIST的完整代码:
softmax_tf_mnist.py

# -*- coding: utf-8 -*-
‘‘‘softmax回归测试MNIST数据集‘‘‘
import input_data
import tensorflow as tf
#导入MNIST数据
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
#softmax回归模型中的x,W,b
x = tf.placeholder("float", [None, 784])
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
#softmax回归模型
y = tf.nn.softmax(tf.matmul(x,W) + b)
y_ = tf.placeholder("float", [None,10])
#计算交叉熵
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
#设置TensorFlow用梯度下降算法以0.01的学习速率最小化交叉熵
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
#初始化变量
init = tf.initialize_all_variables()
#评估模型
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
#开启Tesnsorflow
sess = tf.Session()
sess.run(init)
#循环训练模型
for i in range(1000):
  batch = mnist.train.next_batch(100)
  sess.run(train_step,feed_dict={x: batch[0], y_: batch[1]})
#输出结果
print "softmax回归测试MNIST数据集正确率:"
print sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})

结果,为了减少运行时间,我直接把训练次数设置的很小.
训练次数设置为1000时:

技术分享

3.卷积神经网络测试MNIST

1)卷积神经网络
一篇讲解cnn的博文:
http://www.36dsj.com/archives/24006

2)测试MNIST

yhh@ubuntu:~/Test$ python cnn_tf_mnist.py

如果未导入MNIST数据集的话,先运行:

yhh@ubuntu:~/Test$ python input_data.py

结果,为了减少运行时间,我直接把训练次数设置的很小.

训练次数设置为1000时:

技术分享

卷积神经网络测试MNIST的完整代码:
cnn_tf_mnist.py

# -*- coding: utf-8 -*-
‘‘‘卷积神经网络测试MNIST数据‘‘‘
#导入MNIST数据
import input_data
import tensorflow as tf
mnist = input_data.read_data_sets(‘MNIST_data/‘, one_hot=True)
sess = tf.InteractiveSession()
x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10])
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
sess.run(tf.initialize_all_variables())
#权重初始化函数,用一个较小的正数来初始化偏置项
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‘)

def max_pool_2x2(x):
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding=‘SAME‘)
#第一层卷积
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
#把x变成一个4d向量
x_image = tf.reshape(x, [-1,28,28,1])
#把x_image和权值向量进行卷积,加上偏置项,然后应用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])
b_conv2 = bias_variable([64])

h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
#密集连接层
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])

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)
#添加一个softmax层,就像softmax regression一样
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
#训练设置
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
sess.run(tf.initialize_all_variables())
#训练
for i in range(1000):
  batch = mnist.train.next_batch(50)
  if i%100 == 0:
    train_accuracy = accuracy.eval(feed_dict={
        x:batch[0], y_: batch[1], keep_prob: 1.0})
    print "-->step %d, training accuracy %.4f"%(i, train_accuracy)
  train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
#最终评估
print "卷积神经网络测试MNIST数据集正确率: %g"%accuracy.eval(feed_dict={
    x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})

4.Tensorflow学习文档

Tenssorflow中文社区:
http://www.tensorfly.cn/tfdoc/tutorials/mnist_pros.html

Tensorflow快速入门2--实现手写数字识别

标签:add   markdown   nis   equal   nes   梯度下降   分类   sam   索引   

原文地址:http://blog.csdn.net/yhhyhhyhhyhh/article/details/54574021

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!