tensorflow-顯示mnist圖像並且加載模型識別單張圖像(二)

通過上一遍文章,我們能夠得到比較簡單的mnist訓練模型。

在根目錄的save文件夾下有四個文件,保存的是訓練模型,文件具體內容自行查找資料,我們加載模型時,只需定義出save文件夾下的路徑即可

下面代碼包含:

一:從測試集中隨機挑選出兩張圖像用於顯示並且識別

二:加載訓練模型 

import tensorflow as tf 
#加載mnist庫,從在測試集中挑選要測試的圖片
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
import pylab#用於畫圖,很方便
########################################################################
pylab.mpl.rcParams['font.sans-serif'] = ['SimHei'] # 若不添加,中文無法在圖中顯示
# import matplotlib
# matplotlib.rcParams['axes.unicode_minus']=False # 若不添加,無法在圖中顯示負號
###########################################################################
 

tf.reset_default_graph()#可以清空默認圖裏所有的節點。
#輸入測試數據
x = tf.placeholder(tf.float32, [None, 784]) #測試圖片

#權重和偏置
W = tf.Variable(tf.random_normal([784, 10]))
b = tf.Variable(tf.zeros([10]))
 
#構建模型
pred = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax分類
 
#保存或者打開模型
saver = tf.train.Saver()
#保存或者打開模型的路徑
model_path = "save/model"
###############################################################################
#啓動會議
with tf.Session() as sess:
    #變量初始化
    sess.run(tf.global_variables_initializer())
    #打開訓練好的模型
    saver.restore(sess, model_path)
    #測試模型
    #從測試集中隨機取2張圖片,圖片賦給batch_xs,對應的標籤賦給batch_ys
    batch_xs,batch_ys = mnist.test.next_batch(2)
    #output爲2張圖片通過softmax得到的最大概率對應的標籤
    output = tf.argmax(pred, 1)
    #正式運行,先X輸入2張測試圖片,再output得到2張圖片概率最大對應的標籤並賦給outputval
    #最後pred得到2張圖片再0-9上各自的概率
    outputval, predv = sess.run([output, pred], feed_dict={x: batch_xs})

    print(outputval, predv)
    #######################################################################
    print(batch_xs.shape)
    pylab.subplot(121) 
    im = batch_xs[0]
    im = im.reshape(-1, 28)#把原本在mnist中爲一行的數據變成二維的28列矩陣,-1:不用指定具體爲多少行
    pylab.title('該圖片中的數字爲:'+ str(outputval[0]))
    pylab.imshow(im)
 
    pylab.subplot(122)
    im = batch_xs[1]
    im = im.reshape(-1, 28)
    pylab.title('該圖片中的數字爲:' + str(outputval[1]))
    pylab.imshow(im)
    pylab.show()

結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章