# encoding:utf-8
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
batch_size = 32
n_batch = mnist.train.num_examples // batch_size
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])
dr = tf.placeholder(tf.float32)
def weight_variable(shape):
return tf.Variable(tf.truncated_normal(shape, stddev=0.1))
def bias_variable(shape):
return tf.Variable(tf.constant(0.1, shape=shape))
def conv2d(x, w):
return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(input):
return tf.nn.max_pool(input, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# 转变输入数据形式
x_input = tf.reshape(x, [-1, 28, 28, 1])
# 定义神经网络
# 卷积层1
# 5*5的采样窗口,32个卷积核从1个平面抽取特征
w1 = weight_variable([5, 5, 1, 32])
b1 = bias_variable([32])
w_b1 = conv2d(x_input, w1) + b1
# 28*28*1 的图片卷积之后变为28*28*32
# 激活函数激活
conv_1 = tf.nn.relu(w_b1)
# 池化 池化后的大小为14*14*32
l1 = max_pool_2x2(conv_1)
# 卷积层2
# 5*5的采样窗口,64个卷积核从1个平面抽取特征
w2 = weight_variable([5, 5, 32, 64])
b2 = bias_variable([64])
w_b2 = conv2d(l1, w2) + b2
# 28*28*32 的图片卷积之后变为14*14*64
# 激活函数激活
conv_2 = tf.nn.relu(w_b2)
# 池化 池化后的大小为7*7*64
l2 = max_pool_2x2(conv_2)
# 全连接层1
w3 = weight_variable([7*7*64, 1024])
b3 = bias_variable([1024])
fc_input = tf.reshape(l2, [-1, 7*7*64])
fc1 = tf.matmul(fc_input, w3) + b3
# 激活、dropout
fc1_ = tf.nn.relu(fc1)
fc1_out = tf.nn.dropout(fc1_, dr)
# 全连接层2
w4 = weight_variable([1024, 10])
b4 = bias_variable([10])
fc2 = tf.matmul(fc1_out, w4) + b4
fc2_out = tf.nn.sigmoid(fc2)
pre = tf.nn.softmax(fc2_out)
# 损失函数
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=fc2_out))
train_step = tf.train.AdamOptimizer(0.001).minimize(loss)
init = tf.global_variables_initializer()
# 准确率
accuracy = tf.equal(tf.argmax(y, 1), tf.argmax(pre, 1))
acc = tf.reduce_mean(tf.cast(accuracy, tf.float32))
save = tf.train.Saver()
with tf.Session() as sess:
sess.run(init)
for epoch in range(20):
for i in range(n_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys, dr: 0.7})
batch_xt, batch_yt = mnist.test.next_batch(batch_size)
acc2 = sess.run(acc, feed_dict={x: batch_xt, y: batch_yt, dr: 1.0})
print(acc2)
if i % 10 == 0:
save.save(sess, "./checkpoint/model_%s.ckpt" % i)
acc1 = sess.run(acc, feed_dict={x: mnist.test.images, y: mnist.test.labels, dr: 1.0})
print("epoch %d : acc = %f" % (epoch, acc1))
save.save(sess, "./checkpoint/final_model.ckpt")
评论1