假設我們已經安裝好了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()
ok,貼一下效果圖
輸出:
最後再貼一個cifar10的,感覺我的輸入數據有點問題,因爲直接讀cifar10的數據測試是沒問題的,但是換成自己的圖片做預處理後輸入結果就有問題,(參考:cv2讀入的數據是BGR順序,PIL讀入的數據是RGB順序,cifar10的數據是RGB順序),哪位童鞋能指出來記得留言告訴我
# -*- coding:utf-8 -*-
from sys import path
import numpy as np
import tensorflow as tf
import time
import cv2
from PIL import Image
path.append('../..')
from common import extract_cifar10
from common import inspect_image
#初始化單個卷積核上的參數
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)
#卷積操作
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def main():
#定義會話
sess = tf.InteractiveSession()
#聲明輸入圖片數據,類別
x = tf.placeholder('float',[None,32,32,3])
y_ = tf.placeholder('float',[None,10])
#第一層卷積層
W_conv1 = weight_variable([5, 5, 3, 64])
b_conv1 = bias_variable([64])
#進行卷積操作,並添加relu激活函數
conv1 = tf.nn.relu(conv2d(x,W_conv1) + b_conv1)
# pool1
pool1 = tf.nn.max_pool(conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1],padding='SAME', name='pool1')
# norm1
norm1 = tf.nn.lrn(pool1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75,name='norm1')
#第二層卷積層
W_conv2 = weight_variable([5,5,64,64])
b_conv2 = bias_variable([64])
conv2 = tf.nn.relu(conv2d(norm1,W_conv2) + b_conv2)
# norm2
norm2 = tf.nn.lrn(conv2, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75,name='norm2')
# pool2
pool2 = tf.nn.max_pool(norm2, ksize=[1, 3, 3, 1],strides=[1, 2, 2, 1], padding='SAME', name='pool2')
#全連接層
#權值參數
W_fc1 = weight_variable([8*8*64,384])
#偏置值
b_fc1 = bias_variable([384])
#將卷積的產出展開
pool2_flat = tf.reshape(pool2,[-1,8*8*64])
#神經網絡計算,並添加relu激活函數
fc1 = tf.nn.relu(tf.matmul(pool2_flat,W_fc1) + b_fc1)
#全連接第二層
#權值參數
W_fc2 = weight_variable([384,192])
#偏置值
b_fc2 = bias_variable([192])
#神經網絡計算,並添加relu激活函數
fc2 = tf.nn.relu(tf.matmul(fc1,W_fc2) + b_fc2)
#輸出層,使用softmax進行多分類
W_fc2 = weight_variable([192,10])
b_fc2 = bias_variable([10])
y_conv=tf.maximum(tf.nn.softmax(tf.matmul(fc2, W_fc2) + b_fc2),1e-30)
#
saver = tf.train.Saver()
saver.restore(sess , 'model_data/model.ckpt')
#input
im = Image.open('images/dog8.jpg')
im.show()
im = im.resize((32,32))
# r , g , b = im.split()
# im = Image.merge("RGB" , (r,g,b))
print im.size , im.mode
im = np.array(im).astype(np.float32)
im = np.reshape(im , [-1,32*32*3])
im = (im - (255 / 2.0)) / 255
batch_xs = np.reshape(im , [-1,32,32,3])
#print batch_xs
#獲取cifar10數據
# cifar10_data_set = extract_cifar10.Cifar10DataSet('../../data/')
# batch_xs, batch_ys = cifar10_data_set.next_train_batch(1)
# print batch_ys
output = sess.run(y_conv , feed_dict={x:batch_xs})
print output
print 'the out put is :' , np.argmax(output)
#關閉會話
sess.close()
if __name__ == '__main__':
main()