Sample Code
# 去掉 warning
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
# 去掉 warning
old_v = tf.logging.get_verbosity()
tf.logging.set_verbosity(tf.logging.ERROR)
# 引入 input_data 文件,这个文件用于去mnist页面获取mnist数据
from tensorflow.examples.tutorials.mnist import input_data
# 读取 mnist 数据集, 将取到的数据集放到 E:\mnist 文件夹
mnist = input_data.read_data_sets('E:\mnist', one_hot = True)
# 计算精确度
def computer_accuracy(v_xs, v_ys):
global prediction
y_pre = sess.run(prediction, feed_dict = {xs: v_xs, keep_prob: 1})
correct_prediction = tf.equal(tf.argmax(y_pre, 1), tf.argmax(v_ys, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
result = sess.run(accuracy, feed_dict = {xs: v_xs, ys: v_ys, keep_prob: 1})
return result
# 定义权重 weight
def weight_variables(shape):
initial = tf.truncated_normal(shape, stddev = 0.1)
return tf.Variable(initial)
# 定义 biases
def bias_variable(shape):
initial = tf.constant(0.1, shape = shape)
return tf.Variable(initial)
# 定义 卷积层
def conv2d(x, W):
# stride [1, x_movement, y_movement, 1]
# Must stride[0] = stride[3] = 1
return tf.nn.conv2d(x, W, strides = [1, 1, 1, 1], padding = 'SAME')
# 定义 池化层
def max_pool_2x2(x):
# stride [1, x_movement, y_movement, 1]
# Must stride[0] = stride[3] = 1
return tf.nn.max_pool(x, ksize = [1, 2, 2, 1], strides = [1, 2, 2, 1], padding = 'SAME')
# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 784]) / 255 # 28*28
ys = tf.placeholder(tf.float32, [None, 10])
# 定义概率,以 1 - keep_prob 概率去掉神经元,也就是说神经元保留百分比为 keep_prob
keep_prob = tf.placeholder(tf.float32)
x_image = tf.reshape(xs, [-1, 28, 28, 1])
# print(x_image.shape) # [n_samples, 28, 28, 1]
# 第一层 卷积层 + 池化层
# 卷积层
# patch 5x5, in size 1, out size 32, 1 可以理解为 image 的厚度,32 为 32 个卷积核,也就是说输出厚度为 32
W_conv1 = weight_variables([5, 5, 1, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # output size 28x28x32
# 池化层
# patch 2x2, 并且步长为 2x2, 所以池化操作后, 长度和宽度都减半 为 14x14
h_pool1 = max_pool_2x2(h_conv1) # output size 14x14x32
# 第二层 卷积层 + 池化层
# 卷积层
# patch 5x5, in size 32, out size 64, 32 可以理解为 image 的厚度,64 为 64 个卷积核,也就是说输出厚度为 64
W_conv2 = weight_variables([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # output size 14x14x64
# 池化层
# patch 2x2, 并且步长为 2x2, 所以池化操作后, 长度和宽度都减半 为 7x7
h_pool2 = max_pool_2x2(h_conv2) # output size 7x7x64
# 第三层 全连接层 + dropout
W_fc1 = weight_variables([7*7*64, 1024])
b_fc1 = bias_variable([1024])
# [n_sample , 7, 7, 64] ->> [n_sample, 7x7x64]
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) # Flatten操作。把图片展平
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
# dropout 防止 overfitting
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# 第四层 全连接层 -> 分类
W_fc2 = weight_variables([1024, 10])
b_fc2 = weight_variables([10])
prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
# 损失函数使用交叉熵损失函数 cross_entropy
cross_entropy = tf.reduce_mean(- tf.reduce_sum(ys * tf.log(prediction), reduction_indices = [1]))
# 使用梯度下降法进行训练 -> learning rate 0.1
# train_step = tf.train.GradientDescentOptimizer(0.1).minimize(cross_entropy)
# 使用 Adam 进行训练
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
# 全局变量初始化
init = tf.global_variables_initializer()
# 开始训练
with tf.Session() as sess:
sess.run(init)
for i in range(1001):
# 小批量梯度下降
batch_xs, batch_ys = mnist.train.next_batch(100) # 每次取出 100 个用于计算loss, 来梯度下降
sess.run(train_step, feed_dict = {xs: batch_xs, ys: batch_ys, keep_prob: 0.5})
if i % 50 == 0:
# 取出 test set 的前 1000 个 image 计算 accuracy
print('%4d: %6.4f' %(i, computer_accuracy(mnist.test.images[:1000], mnist.test.labels[:1000])))
-
采用 AdamOptimizer 的 accuracy
-
采用 GradientDescentOptimizer 的 accuracy
后言
- 按理说,AdamOptimizer应该比 GradientDescentOptimizer 的 accuracy 高的,但是。。
- 事实无绝对,具体采用哪种梯度下降,还需实验!