您的位置:首页 > 其它

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

2017-07-12 09:52 501 查看


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

环境: 

虚拟机ubuntun16.0.4 

Tensorflow 版本:0.12.0(仅使用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)
1
2
3
1
2
3

每一个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
1
2
1
2

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})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

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

训练次数设置为1000时:




3.卷积神经网络测试MNIST

1)卷积神经网络 

一篇讲解cnn的博文: 
http://www.36dsj.com/archives/24006

2)测试MNIST
yhh@ubuntu:~/Test$ python cnn_tf_mnist.py
1
1

如果未导入MNIST数据集的话,先运行:
yhh@ubuntu:~/Test$ python input_data.py
1
1

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

训练次数设置为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})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72

其实Tensorflow0.12.0安装时下载的源码及models中也有mnist卷积神经网络测速的例子。 

在: 



可以将整个文件夹复制到home目录下,便于查看和修改。 

可以直接运行该demo:
yhh@ubuntu:~/Test$ python ./tensorflow/models/image/mnist/convolutional.py
1
2
1
2

部分输出结果:




4.Tensorflow学习文档

Tenssorflow中文社区: 
http://www.tensorfly.cn/tfdoc/tutorials/mnist_pros.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: