上一篇文章使用最简单的softmax分类大概过了一下tensorflow的运行机制:
(1)首先构建一个“算法图(也叫作inference图)”,这个图包含了很多的节点,有变量节点也有运算操作节点
(2)为了学习得到图中变量节点的数值,定义一个损失函数,并选择一个优化算法,(构建一个训练图)
(3)在tensorflow的session中去运行训练的图
【圈点:python代码的目标只是用来构建一个可以在外部运行的计算图,并且安排好计算图的哪些部分应该被运行】
该篇文章在上一篇文章的基础上,将softmax分类算法的特征输入从原始的灰度图像像素值改为一个简单神经网络的输出,主函数代码如下,数据处理代码和上一篇文章给出的一样。
测试结果acc在99.2左右
import tensorflow as tf
import mnist_data_process
import numpy as np
data_path = r'./mnist_data'
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')
# 一个简单的两层卷积,一层全连接层以及一层分类输出层的网络
def get_net_v1(input_data, keep_prob):
# layer_1:
# 这个就是卷积核的定义,5*5是卷积核的大小,1是输入的特征图的通道,这里第一层的输入是原始灰度图像因此是1。32是输出特征图的通道数
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
# 卷积-》激活-》maxpooling
h_conv1 = max_pool_2x2(tf.nn.relu(conv2d(input_data, W_conv1) + b_conv1))
# layer_2:
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
# 卷积-》激活-》maxpooling
h_conv2 = max_pool_2x2(tf.nn.relu(conv2d(h_conv1, W_conv2) + b_conv2))
# fully-connect layer-1:
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
flat_conv2 = tf.reshape(h_conv2, [-1, 7*7*64])
# 卷积-》激活
h_fc1 = tf.nn.relu(tf.matmul(flat_conv2, W_fc1) + b_fc1)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# fully-connect layer-2:(classifier layer)
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
# 卷积-》激活
net_simple = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
return net_simple
def mnist_v2():
# Python代码的目的是用来构建这个可以在外部运行的计算图,以及安排计算图的哪一部分应该被运行
input_data = tf.placeholder('float', [None, 28, 28, 1])
input_labels = tf.placeholder('float', [None, 10])
# TODO:1、构建图
keep_prob = tf.placeholder("float")
v1_net = get_net_v1(input_data, keep_prob)
# TODO:2、定义损失函数
cross_entropy_loss = -tf.reduce_sum(input_labels * tf.log(v1_net))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy_loss)
correct_prediction = tf.equal(tf.argmax(v1_net, 1), tf.argmax(input_labels, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
# TODO:3、始化所有的参数
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.6)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
init = tf.initialize_all_variables()
sess.run(init)
# TODO:4、准备数据
# 这里是读入tfrecord的数据并且转化为正常的数据矩阵
mnist_data = mnist_data_process.read_data_sets(data_path, one_hot=True, reshape=False)
# TODO:5、开始训练,定义训练的迭代轮数
iter_num = 20000
log_step = 100
for index in range(iter_num):
batch_xs, batch_ys = mnist_data.train.next_batch(100)
if index % log_step == 0:
train_accuracy = sess.run(accuracy, feed_dict={
input_data: batch_xs, input_labels: batch_ys, keep_prob: 1.0})
print("step %d, training accuracy %g" % (index, train_accuracy))
sess.run(train_step, feed_dict={input_data: batch_xs, input_labels: batch_ys, keep_prob: 0.5})
# TODO:6、使用训练完的参数对测试数据进行测试
data = mnist_data.test.images
test_labels = tf.argmax(mnist_data.test.labels, 1)
data_num = data.shape[0]
batch_size = 100
iter_data_num = int(data_num/batch_size)
test_y = []
for index in range(iter_data_num):
test_data = data[index*batch_size:(index+1)*batch_size]
_y = sess.run(v1_net, feed_dict={input_data: test_data, keep_prob: 1.0})
if index == 0:
test_y = _y
else:
test_y = np.vstack((test_y, _y))
test_y = np.array(test_y)
predict_labels = tf.argmax(test_y, 1)
correct_prediction = tf.equal(predict_labels, test_labels)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print(sess.run(accuracy))
# test_accuracy = sess.run(accuracy, feed_dict={input_data: test_data, input_labels: test_labels, keep_prob: 1.0})
# print("test accuracy %g" % test_accuracy)
if __name__ == '__main__':
mnist_v2()