TensorFlow中关于MNIST的学习
2017-03-06 20:09
183 查看
TensorFlow中有两部分都介绍了MNIST,其中MNIST for ML Beginners介绍了一些关于Machine Learning的基本知识。这里只介绍Deep MNIST for Experts部分
类InteractiveSession
TensorFlow中既可以用tf.Session()来生成graph
也可以使用tf.InteractiveSession()进行交互式对话
之后,定义交叉熵来表示模型的代价函数
训练模型
评估模型
打破梯度更新对称性,w服从正态分布,方差为0.1
卷积和池化
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)
ksize为filter的大小,第一个参数代表batch的数量,一般为1,第二和第三个参数代表filter大小,第四个参数是channel的数量
strides为步长,和上面对应
第一层卷积层
为了应用卷积层,首先需要将x转换为一个4d的tensor。最后一个维度代表通道数
现在得到的图像大小为14x14
第二层卷积层
得到的图像大小为7x7
全连接层,共有1024个神经元
Dropout
主要为了防止过拟合
最后一层
训练与评估
加载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与variablesess = 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}))
相关文章推荐
- 关于Ubuntu16.04+Tensorflow学习笔记 MNIST导入
- tensorflow学习笔记四:mnist实例--用简单的神经网络来训练和测试
- tensorflow 学习笔记(1) MNIST for beginners
- TensorFlow官方教程学习笔记(四)——MNIST数据集的读取
- 用tensorflow实现usps和mnist数据集的迁移学习
- Tensorflow深度学习入门——采用卷积和池化优化训练MNIST数据——代码+注释
- TensorFLow学习(一),Mnist入门
- TensorFlow学习_02_CNN卷积神经网络_Mnist手写数字识别
- TensorFlow学习_01_安装_基本操作_可视化结构、过程_Mnist
- tensorflow学习笔记四:mnist实例--用简单的神经网络来训练和测试(MNIST For ML Beginners)
- 深度学习框架TensorFlow学习(一)------关于Tensorflow的简介和配置
- tensorflow学习笔记五:mnist实例--卷积神经网络(CNN)
- tensorflow学习笔记四:mnist实例--用简单的神经网络来训练和测试
- TensorFlow官方教程学习笔记(三)——MNIST入门(续)
- tensorflow学习笔记五:mnist实例--卷积神经网络(CNN)
- tensorflow学习笔记之使用tensorflow进行MNIST分类(1)
- TensorFlow官方教程学习 Deep MNIST for Experts
- 用tensorflow实现usps和mnist数据集的迁移学习
- TensorFlow学习笔记--mnist可视化版本
- 学习tensorflow,浅析MNIST的python代码