上篇博客讲述了使用了tensorflow 用全连接网络完成mnist的分类,我们将博客中的fully contact net 替换成 convolutional net测试mnist分类
import tensorflow as tf
import numpy as np
from tf_utils import *
import tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
#定义下权重变量,防止每次定义卷积层重新定义一次
def w_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
#定义下偏置,防止重复定义
def b_variable(shape):
return tf.Variable(tf.constant(0.1, shape=shape))
#定义卷积
def conv2d(input_, w):
return tf.nn.conv2d(input_, w, strides = [1, 1, 1, 1], padding = 'SAME')
#定义池化
def max_pool(input_):
return tf.nn.max_pool(input_, ksize = [1, 2, 2, 1], strides = [1, 2, 2, 1], padding = 'SAME')
#定义标签维度
label_dim = 10
#定义batch_size维度
batch_size = 100
#定义图像维度
image_dim = 784
input_image = tf.placeholder(tf.float32, [None, image_dim])
input_label = tf.placeholder(tf.float32, [None, label_dim])
image = tf.reshape(input_image, [-1, 28, 28, 1])
#第一层卷积
w1 = w_variable([5, 5, 1, 32])
b1 = b_variable([32])
conv1 = tf.nn.relu(conv2d(image, w1) + b1)
output1 = max_pool(conv1)
#第二层卷积
w2 = w_variable([5, 5, 32, 64])
b2 = b_variable([64])
conv2 = tf.nn.relu(conv2d(output1, w2) + b2)
output2 = max_pool(conv2)
#全连接网络第一层
fc1 = tf.reshape(output2, [-1, 7*7*64])
w3 = w_variable([7*7*64, 1024])
b3 = b_variable([1024])
fc2 = tf.nn.relu(tf.matmul(fc1, w3) +b3)
#全连接网络第二层
w4 = w_variable([1024,10])
b4 = b_variable([10])
fc3 = tf.nn.softmax(tf.matmul(fc2, w4) +b4)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(input_label * tf.log(fc3)))
train_loss = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
prediction = tf.equal(tf.argmax(input_label, 1), tf.argmax(fc3, 1))
accuary = tf.reduce_sum(tf.cast(prediction, "float"))
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(1000):
batch_x, batch_y = mnist.train.next_batch(batch_size)
sess.run(train_loss, feed_dict = {input_image : batch_x, input_label : batch_y})
if i % 10 == 0:
print(sess.run(accuary, feed_dict = {input_image:batch_x, input_label:batch_y}))