假設我們已經安裝好了tensorflow。
一般在安裝好tensorflow后,都會跑它的demo,而最常見的demo就是手寫數字識別的demo,也就是mnist數據集。
然而我們僅僅是跑了它的demo而已,可能很多人會有和我一樣的想法,如果拿來一張數字圖片,如何應用我們訓練的網絡模型來識別出來,下面我們就以mnist的demo來實現它。
1.訓練模型
首先我們要訓練好模型,并且把模型model.ckpt保存到指定文件夾
saver = tf.train.Saver() saver.save(sess, "model_data/model.ckpt")
將以上兩行代碼加入到訓練的代碼中,訓練完成后保存模型即可,如果這部分有問題,你可以百度查閱資料,tensorflow怎么保存訓練模型,在這里我們就不羅嗦了。
2.測試模型
我們訓練好模型后,將它保存在了model_data文件夾中,你會發現文件夾中出現了4個文件

然后,我們就可以對這個模型進行測試了,將待檢測圖片放在images文件夾下,執行
# -*- coding:utf-8 -*- import cv2 import tensorflow as tf import numpy as np from sys import path path.append('../..') from common import extract_mnist #初始化單個卷積核上的參數 def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) #初始化單個卷積核上的偏置值 def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) #輸入特征x,用卷積核W進行卷積運算,strides為卷積核移動步長, #padding表示是否需要補齊邊緣像素使輸出圖像大小不變 def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') #對x進行最大池化操作,ksize進行池化的范圍, def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME') def main(): #定義會話 sess = tf.InteractiveSession() #聲明輸入圖片數據,類別 x = tf.placeholder('float',[None,784]) x_img = tf.reshape(x , [-1,28,28,1]) W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) W_conv2 = weight_variable([5,5,32,64]) b_conv2 = bias_variable([64]) W_fc1 = weight_variable([7*7*64,1024]) b_fc1 = bias_variable([1024]) W_fc2 = weight_variable([1024,10]) b_fc2 = bias_variable([10]) saver = tf.train.Saver(write_version=tf.train.SaverDef.V1) saver.restore(sess , 'model_data/model.ckpt') #進行卷積操作,并添加relu激活函數 h_conv1 = tf.nn.relu(conv2d(x_img,W_conv1) + b_conv1) #進行最大池化 h_pool1 = max_pool_2x2(h_conv1) #同理第二層卷積層 h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) #將卷積的產出展開 h_pool2_flat = tf.reshape(h_pool2,[-1,7*7*64]) #神經網絡計算,并添加relu激活函數 h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1) + b_fc1) #輸出層,使用softmax進行多分類 y_conv=tf.nn.softmax(tf.matmul(h_fc1, W_fc2) + b_fc2) # mnist_data_set = extract_mnist.MnistDataSet('../../data/') # x_img , y = mnist_data_set.next_train_batch(1) im = cv2.imread('images/888.jpg',cv2.IMREAD_GRAYSCALE).astype(np.float32) im = cv2.resize(im,(28,28),interpolation=cv2.INTER_CUBIC) #圖片預處理 #img_gray = cv2.cvtColor(im , cv2.COLOR_BGR2GRAY).astype(np.float32) #數據從0~255轉為-0.5~0.5 img_gray = (im - (255 / 2.0)) / 255 #cv2.imshow('out',img_gray) #cv2.waitKey(0) x_img = np.reshape(img_gray , [-1 , 784]) print x_img output = sess.run(y_conv , feed_dict = {x:x_img}) print 'the y_con : ', '/n',output print 'the predict is : ', np.argmax(output) #關閉會話 sess.close() if __name__ == '__main__': main()
新聞熱點
疑難解答