最近剛接觸tensorflow期丰,同樣和廣大網(wǎng)友一樣采用MINIST數(shù)據(jù)來做手寫識(shí)別群叶,內(nèi)容以注釋的形式在代碼里了
模型訓(xùn)練和保存
1.首先下載MINIST數(shù)據(jù)庫(下載地址) ,四個(gè)文件下載后放到和你的python文件同一個(gè)目錄下钝荡,不用解壓街立,然后輸入,其中e2.jpg在文末可下載
#coding=utf-8
# 載入MINIST數(shù)據(jù)需要的庫
from tensorflow.examples.tutorials.mnist import input_data
# 保存模型需要的庫
from tensorflow.python.framework.graph_util import convert_variables_to_constants
from tensorflow.python.framework import graph_util
# 導(dǎo)入其他庫
import tensorflow as tf
import cv2
import numpy as np
#獲取MINIST數(shù)據(jù)
mnist = input_data.read_data_sets(".",one_hot = True)
# 創(chuàng)建會(huì)話
sess = tf.InteractiveSession()
#占位符
x = tf.placeholder("float", shape=[None, 784], name="Mul")
y_ = tf.placeholder("float",shape=[None, 10], name="y_")
#變量
W = tf.Variable(tf.zeros([784,10]),name='x')
b = tf.Variable(tf.zeros([10]),'y_')
#權(quán)重
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 max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
#相關(guān)變量的創(chuàng)建
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1,28,28,1])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
#激活函數(shù)
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
keep_prob = tf.placeholder("float",name='rob')
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
#用于訓(xùn)練用的softmax函數(shù)
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2,name='res')
#用于訓(xùn)練作完后埠通,作測試用的softmax函數(shù)
y_conv2=tf.nn.softmax(tf.matmul(h_fc1, W_fc2) + b_fc2,name="final_result")
#交叉熵的計(jì)算赎离,返回包含了損失值的Tensor。
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
#優(yōu)化器端辱,負(fù)責(zé)最小化交叉熵
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
#計(jì)算準(zhǔn)確率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
#初始化所以變量
sess.run(tf.global_variables_initializer())
# 保存輸入輸出梁剔,可以為之后用
tf.add_to_collection('res', y_conv)
tf.add_to_collection('output', y_conv2)
tf.add_to_collection('x', x)
#訓(xùn)練開始
for i in range(20000):
batch = mnist.train.next_batch(50)
if i%100 == 0:
train_accuracy = accuracy.eval(feed_dict={
x:batch[0], y_: batch[1], keep_prob: 1.0})
print "step %d, training accuracy %g"%(i, train_accuracy)
#run()可以看做輸入相關(guān)值給到函數(shù)中的占位符虽画,然后計(jì)算的出結(jié)果,這里將batch[0]荣病,給xbatch[1]給y_
train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
#將當(dāng)前圖設(shè)置為默認(rèn)圖
graph_def = tf.get_default_graph().as_graph_def()
#將上面的變量轉(zhuǎn)化成常量码撰,保存模型為pb模型時(shí)需要,注意這里的final_result和前面的y_con2是同名,只有這樣才會(huì)保存它个盆,否則會(huì)報(bào)錯(cuò)灸拍,
# 如果需要保存其他tensor只需要讓tensor的名字和這里保持一直即可
output_graph_def = tf.graph_util.convert_variables_to_constants(sess,
graph_def, ['final_result'])
#保存前面訓(xùn)練后的模型為pb文件
with tf.gfile.GFile("grf.pb", 'wb') as f:
f.write(output_graph_def.SerializeToString())
#用saver 保存模型
saver = tf.train.Saver()
saver.save(sess, "model_data/model")
#導(dǎo)入圖片,同時(shí)灰度化
im = cv2.imread('pic/e2.jpg',cv2.IMREAD_GRAYSCALE)
#反轉(zhuǎn)圖像砾省,因?yàn)閑2.jpg為白底黑字
im =reversePic(im)
cv2.namedWindow("camera", cv2.WINDOW_NORMAL);
cv2.imshow('camera',im)
cv2.waitKey(0)
#調(diào)整大小
im = cv2.resize(im,(28,28),interpolation=cv2.INTER_CUBIC)
x_img = np.reshape(im , [-1 , 784])
#輸出圖像矩陣
# print x_img
#用上面導(dǎo)入的圖片對(duì)模型進(jìn)行測試
output = sess.run(y_conv2 , feed_dict={x:x_img })
# print 'the y_con : ', '\n',output
print 'the predict is : ', np.argmax(output)
print "test accracy %g"%accuracy.eval(feed_dict={
x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})
輸出:
沒有CUDA加速鸡岗,訓(xùn)練的會(huì)比較慢,但都可以訓(xùn)練编兄,只是速度區(qū)別
1)其中用Saver保存模型的代碼:
saver = tf.train.Saver()
saver.save(sess, "model_data/model")
最終會(huì)產(chǎn)生model_data文件夾轩性,其中包含了:
2)保存模型為pb格式的代碼:
#將當(dāng)前圖設(shè)置為默認(rèn)圖
graph_def = tf.get_default_graph().as_graph_def()
#將上面的變量轉(zhuǎn)化成常量,保存模型為pb模型時(shí)需要,注意這里的final_result和前面的y_con2是同名狠鸳,只有這樣才會(huì)保存它揣苏,否則會(huì)報(bào)錯(cuò),
# 如果需要保存其他tensor只需要讓tensor的名字和這里保持一直即可
output_graph_def = tf.graph_util.convert_variables_to_constants(sess,
graph_def, ['final_result'])
#保存前面訓(xùn)練后的模型為pb文件
with tf.gfile.GFile("grf.pb", 'wb') as f:
f.write(output_graph_def.SerializeToString())
最終在當(dāng)前目錄生成grf.pb文件
模型的恢復(fù):
1.用Saver保存的模型的恢復(fù):
# -*- coding:utf-8 -*-
import cv2
import tensorflow as tf
import numpy as np
from sys import path
#用于將自定義輸入圖片反轉(zhuǎn)
def reversePic(src):
# 圖像反轉(zhuǎn)
for i in range(src.shape[0]):
for j in range(src.shape[1]):
src[i,j] = 255 - src[i,j]
return src
def main():
sess = tf.InteractiveSession()
#模型恢復(fù)
saver=tf.train.import_meta_graph('model_data/model.meta')
saver.restore(sess, 'model_data/model')
graph = tf.get_default_graph()
# 獲取輸入tensor,,獲取輸出tensor
input_x = sess.graph.get_tensor_by_name("Mul:0")
y_conv2 = sess.graph.get_tensor_by_name("final_result:0")
# 也可以上面注釋,通過下面獲取輸出輸入tensor,
# y_conv2 = tf.get_collection('output')[0]
# # x= tf.get_collection('x')[0]
# input_x = graph.get_operation_by_name('Mul').outputs[0]
# keep_prob = graph.get_operation_by_name('rob').outputs[0]
path="pic/e2.jpg"
im = cv2.imread(path,cv2.IMREAD_GRAYSCALE)
#反轉(zhuǎn)圖像件舵,因?yàn)閑2.jpg為白底黑字
im =reversePic(im)
cv2.namedWindow("camera", cv2.WINDOW_NORMAL);
cv2.imshow('camera',im)
cv2.waitKey(0)
# im=cv2.threshold(im, , 255, cv2.THRESH_BINARY_INV)[1];
im = cv2.resize(im,(28,28),interpolation=cv2.INTER_CUBIC)
# im=cv2.threshold(im,200,255,cv2.THRESH_TRUNC)[1]
# im=cv2.threshold(im,60,255,cv2.THRESH_TOZERO)[1]
#數(shù)據(jù)從0~255轉(zhuǎn)為-0.5~0.5
# img_gray = (im - (255 / 2.0)) / 255
x_img = np.reshape(im , [-1 , 784])
output = sess.run(y_conv2 , feed_dict={input_x:x_img})
print 'the predict is %d' % (np.argmax(output))
#關(guān)閉會(huì)話
sess.close()
if __name__ == '__main__':
main()
2.pb模型的恢復(fù):
#coding=utf-8
from __future__ import absolute_import, unicode_literals
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.python.framework.graph_util import convert_variables_to_constants
from tensorflow.python.framework import graph_util
import cv2
import numpy as np
mnist = input_data.read_data_sets(".",one_hot = True)
import tensorflow as tf
#用于將自定義輸入圖片反轉(zhuǎn)
def reversePic(src):
# 圖像反轉(zhuǎn)
for i in range(src.shape[0]):
for j in range(src.shape[1]):
src[i,j] = 255 - src[i,j]
return src
with tf.Session() as persisted_sess:
print("load graph")
with tf.gfile.FastGFile("grf.pb",'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
persisted_sess.graph.as_default()
tf.import_graph_def(graph_def, name='')
# print("map variables")
with tf.Session() as sess:
# tf.initialize_all_variables().run()
input_x = sess.graph.get_tensor_by_name("Mul:0")
y_conv_2 = sess.graph.get_tensor_by_name("final_result:0")
path="pic/e2.jpg"
im = cv2.imread(path,cv2.IMREAD_GRAYSCALE)
#反轉(zhuǎn)圖像卸察,因?yàn)閑2.jpg為白底黑字
im =reversePic(im)
cv2.namedWindow("camera", cv2.WINDOW_NORMAL);
cv2.imshow('camera',im)
cv2.waitKey(0)
# im=cv2.threshold(im, , 255, cv2.THRESH_BINARY_INV)[1];
im = cv2.resize(im,(28,28),interpolation=cv2.INTER_CUBIC)
# im =reversePic(im)
# im=cv2.threshold(im,200,255,cv2.THRESH_TRUNC)[1]
# im=cv2.threshold(im,60,255,cv2.THRESH_TOZERO)[1]
# img_gray = (im - (255 / 2.0)) / 255
x_img = np.reshape(im , [-1 , 784])
output = sess.run(y_conv_2 , feed_dict={input_x:x_img})
print 'the predict is %d' % (np.argmax(output))
#關(guān)閉會(huì)話
sess.close()
其中e2.jpg:
兩個(gè)模型恢復(fù)的輸出結(jié)果都是:
注意:
用MINIST訓(xùn)練出來的模型。主要用來識(shí)別手寫數(shù)字的铅祸,而且對(duì)輸入的圖片要求是近似黑底白字的坑质,所以如果圖片預(yù)處理不合適會(huì)導(dǎo)致識(shí)別率不高。
如果直接用官方的圖片輸 入临梗,則識(shí)別完全沒問題
附官方圖片和e2.jpg的下載地址