代码实现
import tensorflow as tf
import random
from matplotlib import pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
tf.set_random_seed(1)
mnist = input_data.read_data_sets(r'MNIST_data',one_hot=True)
n_class = 10
X = tf.placeholder(dtype=tf.float32,shape=[None,784])
Y = tf.placeholder(dtype=tf.float32,shape=[None,n_class])
W = tf.Variable(tf.random_normal([784,n_class]))
b = tf.Variable(tf.random_normal([n_class]))
h = tf.nn.softmax(tf.matmul(X,W) + b)
cost = tf.reduce_mean(tf.reduce_sum(-(Y * tf.log(h)),axis=1))
trains = tf.train.GradientDescentOptimizer(learning_rate=0.03).minimize(cost)
accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.arg_max(h,1),tf.arg_max(Y,1)),dtype=tf.float32))
train_times = 15
batch_size = 100
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for times in range(train_times):
avg_cost = 0
total_batch = int(mnist.train.num_examples / batch_size)
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
c, _ = sess.run([cost,trains],feed_dict={X: batch_xs,Y: batch_ys})
avg_cost += c / total_batch
print(times+1,'cost: ',avg_cost)
print('训练完毕')
print('准确率: ',sess.run(accuracy,feed_dict={X: mnist.test.images,Y: mnist.test.labels}))
r = random.randint(0,mnist.test.num_examples-1)
print('labels: ',sess.run(tf.argmax(mnist.test.labels[r:r+1],1)))
print('prediction: ',sess.run(tf.argmax(h,1),feed_dict={X: mnist.test.images[r:r+1]}))
plt.imshow(
mnist.test.images[r:r+1].reshape(28,28),
cmap='Greys',
interpolation='nearest'
)
plt.show()
结果如下
画图如下