import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data
#1 读取数据
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
#2 建立模型 使用卷积神经网络
#2.1 输入图像与标签
x = tf.placeholder("float", shape = [None, 28,28,1])
y_ = tf.placeholder("float", shape = [None, 10])
#2.2 搭建卷积神经网络 卷积+卷积+池化+全连接
#2.2.1 卷积层
w1 = tf.Variable(tf.truncated_normal([3, 3, 1, 32])) #高宽3*3 单通道 32个filter
b1 = tf.Variable(tf.zeros([32])) #每个filter初始bias为0
conv1 = tf.nn.conv2d(input=x, filter=w1, strides=[1, 1, 1, 1], padding='SAME') + b1
conv1 = tf.nn.relu(conv1) #进行卷积 非线性激活
#2.2.2 卷积层
w2 = tf.Variable(tf.truncated_normal([3, 3, 32, 32])) #高宽3*3 32通道 32个filter
b2 = tf.Variable(tf.zeros([32])) #每个filter初始bias为0
conv2 = tf.nn.conv2d(input=conv1, filter=w2, strides=[1, 1, 1, 1], padding='SAME') + b2
conv2 = tf.nn.relu(conv2) #进行卷积 非线性激活
#2.2.3 池化
pool = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
#2.2.4 全连接
w = tf.Variable(tf.truncated_normal([14 * 14 * 32, 10], stddev=0.1))
b = tf.Variable(tf.zeros([10]))
pool_reshape = tf.reshape(pool, [-1, 14*14*32])
#2.2.5 输出
y = tf.matmul(pool_reshape, w) + b
#3 损失函数 优化训练
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels = y_, logits = y)
crossEntropyLoss = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer().minimize(crossEntropyLoss)
#4 测试
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#5 开启会话
with tf.Session() as sess:
# 初始化
sess.run(tf.global_variables_initializer())
# 训练
for i in range(501):
batch_xs, batch_ys = mnist.train.next_batch(100)
batch_xs = batch_xs.reshape([100,28,28,1])
sess.run(optimizer, feed_dict={x: batch_xs, y_: batch_ys})
# 测试模型
#if i%100 == 0:
#result = sess.run(accuracy, feed_dict={x: mnist.test.images.reshape([10000,28,28,1]), y_: mnist.test.labels}) * 100
#print(result)
# 测试模型
sum = 0;
for i in range(10000):
sum += sess.run(accuracy, feed_dict={x: mnist.test.images[i].reshape([1,28,28,1]), y_: mnist.test.labels[i].reshape([1,10])})
print(sum)
print(sum/10000)
结果: