您的位置:首页 > 其它

TensorFlow中关于MNIST的学习

2017-03-06 20:09 183 查看
TensorFlow中有两部分都介绍了MNIST,其中MNIST for ML Beginners介绍了一些关于Machine Learning的基本知识。这里只介绍Deep MNIST for Experts部分

加载MNIST数据

类mnist 中存储有training, validation, test用的数据,数据类型为NumPy assays,同时也提供了以minibatches为单位的迭代

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)


类InteractiveSession

TensorFlow中既可以用tf.Session()来生成graph

也可以使用tf.InteractiveSession()进行交互式对话

创建一个Softmax Regression 模型

仍需要定义placeholder与variable

sess = tf.InteractiveSession()

x = tf.placeholder(tf.float32, shape=[None, 784])
y_ = tf.placeholder(tf.float32, shape=[None, 10])
W = tf.Variable(tf.zeros[784, 10])
b = tf.Variable(tf.zeros[10])
sess.run(tf.global_variables_initializer())


之后,定义交叉熵来表示模型的代价函数

cross_entropy = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))


训练模型

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
for _ in range(1000):
batch = mnist.train.next_batch(100)
train_step.run(feed_dict={x: batch[0], y_: batch[1]})


评估模型

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
#tf.cast(x, dtype, name=None) Casts a tensor to a new type.
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels})


改进模型

首先要对变量进行初始化

打破梯度更新对称性,w服从正态分布,方差为0.1

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)


卷积和池化

1.函数tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, data_format=None, name = None)

input: 一个tensor,必须是以下三种类型之一:half, float32, float64

filter: 一个tensor,必须和input的类型相同

strides: 一个ints列表,长度为4的一维数组。

strides[0] = strides[3] = 1. 对于常见的水平和垂直方向步长相同的情况, strides = [1, stride, stride, 1].

padding: “SAME”或者“VALID”

“SAME”是指有padding,stride=1,时输入输出维度一样;“VALID”是指没有padding

use_cudnn_on_gpu: 可选项

data_format: “NHWC”或者”NCHW”

name: 可选项,操作的名称

返回值: 一个tensor

2.函数tf.nn.max_pool(value, ksize, strides, padding, data_format=’NHWC’, name=None)

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')


ksize为filter的大小,第一个参数代表batch的数量,一般为1,第二和第三个参数代表filter大小,第四个参数是channel的数量

strides为步长,和上面对应

第一层卷积层

#5x5, input:1 output:32
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])


为了应用卷积层,首先需要将x转换为一个4d的tensor。最后一个维度代表通道数

x_image = tf.reshape(x, [-1,28,28,1])


h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)


现在得到的图像大小为14x14

第二层卷积层

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)


得到的图像大小为7x7

全连接层,共有1024个神经元

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(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)


最后一层

W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])

y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2


训练与评估

cross_entropy = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=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, tf.float32))
sess.run(tf.global_variables_initializer())
for i in range(20000):
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 %g"%(i, train_accuracy))
train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

print("test accuracy %g"%accuracy.eval(feed_dict={
x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  TensorFlow