第一种Demo
input_data:下载和读MNIST数据模块
"""Functions for downloading and reading MNIST data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import
import gzip
import os
import tempfile
import numpy
from six.moves import urllib
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
# pylint: enable=unused-import
深入MNIST Demo:
# 加载 MNIST data
import input_data
mnist = input_data.read_data_sets("Mnist_data/", one_hot=True)
# InteractiveSession类在运行图的时候,插入一些计算图,
# 这些计算图是由某些操作(operations)构成的
import tensorflow as tf
sess = tf.InteractiveSession()
# 权重在初始化时应该加入少量的噪声来打破对称性以及避免0梯度
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
# 使用ReLU神经元,因此比较好的做法是用一个较小的正数来初始化偏置项,
# 以避免神经元节点输出恒为0的问题
def bias_variable(shape):
initial = tf.constant(0.1, shape = shape)
return tf.Variable(initial)
# 卷积使用1步长(stride size),0边距(padding size)的模板,保证输出和输入是同一个大小
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
# 池化用简单传统的2x2大小的模板做max pooling
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# Create the model
# placeholder 的shape参数是可选的
# 但有了它,TensorFlow能够自动捕捉因数据维度不一致导致的错误
x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10])
# 第一层卷积
# 卷积在每个5x5的patch中算出32个特征
w_conv1 = weight_variable([5, 5, 1, 32])
# 每一个输出通道都有一个对应的偏置量
b_conv1 = bias_variable([32])
# x变成一个4d向量,其第2、第3维对应图片的宽、高
# 最后一维代表图片的颜色通道数,因为是灰度图所以这里的通道数为1
# 如果是rgb彩色图,则为3
x_image = tf.reshape(x, [-1, 28, 28, 1])
# x_image和权值向量进行卷积,加上偏置项
h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)
# ReLU激活函数,最后进行max pooling
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)
# 密集连接层
# 图片尺寸减小到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。
# 我们用一个placeholder来代表一个神经元的输出在dropout中保持不变的概率。
# 这样我们可以在训练过程中启用dropout,在测试过程中关闭dropout
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# readout layer
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))
# 训练模型 更加复杂的ADAM优化器来做梯度最速下降
train_step = tf.train.AdagradOptimizer(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"))
# 变量需要通过seesion初始化后,才能在session中使用
sess.run(tf.initialize_all_variables())
# 整个模型的训练可以通过反复地运行train_step来完成
# 用feed_dict来替代任何张量,并不仅限于替换占位符
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, train 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}))
运行结果:
test accuracy 0.9364
第二种Demo
# 加载 MNIST data
import tensorflow as tf
#导入input_data用于自动下载和安装MNIST数据集
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# InteractiveSession类在运行图的时候,插入一些计算图,
# 这些计算图是由某些操作(operations)构成的
sess = tf.InteractiveSession()
# placeholder 的shape参数是可选的
# 但有了它,TensorFlow能够自动捕捉因数据维度不一致导致的错误
x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10])
# 权重在初始化时应该加入少量的噪声来打破对称性以及避免0梯度
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
# 使用ReLU神经元,因此比较好的做法是用一个较小的正数来初始化偏置项,
# 以避免神经元节点输出恒为0的问题
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
# 卷积使用1步长(stride size),0边距(padding size)的模板,保证输出和输入是同一个大小
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
# 池化用简单传统的2x2大小的模板做max pooling
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# 第一层卷积
# 卷积在每个5x5的patch中算出32个特征
w_conv1 = weight_variable([5, 5, 1, 32])
# 每一个输出通道都有一个对应的偏置量
b_conv1 = bias_variable([32])
# x变成一个4d向量,其第2、第3维对应图片的宽、高
# 最后一维代表图片的颜色通道数,因为是灰度图所以这里的通道数为1
# 如果是rgb彩色图,则为3
x_image = tf.reshape(x, [-1, 28, 28, 1])
# x_image和权值向量进行卷积,加上偏置项
h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)
# ReLU激活函数,最后进行max pooling
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)
# 密集连接层
# 图片尺寸减小到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。
# 我们用一个placeholder来代表一个神经元的输出在dropout中保持不变的概率。
# 这样我们可以在训练过程中启用dropout,在测试过程中关闭dropout
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# readout layer
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))
# 训练模型 更加复杂的ADAM优化器来做梯度最速下降
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"))
# 变量需要通过seesion初始化后,才能在session中使用
sess.run(tf.initialize_all_variables())
# 整个模型的训练可以通过反复地运行train_step来完成
# 用feed_dict来替代任何张量,并不仅限于替换占位符
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, train 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}))
测试结果:
test accuracy 0.9922
注意:两种方式的Demo,主要不同是mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)