TensorFlow-Example5.1 MNIST手写数字识别

TensorFlow-Example5.1 MNIST手写数字识别




Example5.1







In [3]:
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets('MNIST_data/',one_hot=True)#样本标签转化为one_hot编码
Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
In [5]:
print ('输入数据:',mnist.train.images)
print ('输入数据shape:',mnist.train.images.shape)
import pylab
im=mnist.train.images[1]
im=im.reshape(-1,28)
%matplotlib inline#jupyter notebook 输出图像需要
pylab.imshow(im)
pylab.show()
输入数据: [[0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 ...
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]]
输入数据shape: (55000, 784)
In [19]:
tf.reset_default_graph()
x=tf.placeholder(tf.float32,[None,784])#MNIST数据集 28*28=784 None表示可以为任何长度
y=tf.placeholder(tf.float32,[None,10])#数字0~9,共10类
W=tf.Variable(tf.random_normal([784,10]))
b=tf.Variable(tf.zeros([10]))
pred=tf.nn.softmax(tf.matmul(x,W)+b)#Softmax分类
cost=tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred),reduction_indices=1))
learing_rate=0.01
optimizer=tf.train.GradientDescentOptimizer(learing_rate).minimize(cost)
In [25]:
training_epochs=20
batch_size=100
display_step=5
saver=tf.train.Saver()
model_path='Log_E_5.1/model.ckpt'
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for epoch in range(training_epochs):
        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([optimizer,cost],feed_dict={x:batch_xs,y:batch_ys})
            avg_cost+=c/total_batch
        if (epoch+1)%display_step==0:
            print('Epoch:','%04d'%(epoch+1),'cost=','{:.9f}'.format(avg_cost))
    print ('Finished!')
    
    #Test
    correct_prediction=tf.equal(tf.argmax(pred,1),tf.argmax(y,1))
    accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
    print('Accuracy:',accuracy.eval({x:mnist.test.images,y:mnist.test.labels}))
    save_path=saver.save(sess,model_path)
    print('Model saved in file: %s'%save_path)
Epoch: 0005 cost= 1.979183435
Epoch: 0010 cost= 1.299548041
Epoch: 0015 cost= 1.059972996
Epoch: 0020 cost= 0.939491646
Finished!
Accuracy: 0.8116
Model saved in file: Log_E_5.1/model.ckpt
In [32]:
#2nd Session
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    saver.restore(sess,model_path)
    correct_prediction=tf.equal(tf.argmax(pred,1),tf.argmax(y,1))
    accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
    print('Accuracy:',accuracy.eval({x:mnist.test.images,y:mnist.test.labels}))
    output=tf.argmax(pred,1)
    batch_xs,batch_ys=mnist.train.next_batch(2)
    outputval,predv=sess.run([output,pred],feed_dict={x:batch_xs})
    print(outputval)#,predv,batch_ys)
    im=batch_xs[0]
    im=im.reshape(-1,28)
    pylab.imshow(im)
    pylab.show()
    im=batch_xs[1]
    im=im.reshape(-1,28)
    pylab.imshow(im)
    pylab.show()
INFO:tensorflow:Restoring parameters from Log_E_5.1/model.ckpt
Accuracy: 0.8116
[3 1]

发表评论

电子邮件地址不会被公开。 必填项已用*标注