git链接

参考链接
训练模型

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 16 22:26:43 2019@author: lg
"""#coding=utf-8
# 载入MINIST数据需要的库
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 tensorflow as tf
import cv2
import numpy as np
#获取MINIST数据
mnist = input_data.read_data_sets(".",one_hot = True)
# 创建会话
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_')#权重
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')
#相关变量的创建
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])
#激活函数
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)#用于训练用的softmax函数
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2,name='res')
#用于训练作完后,作测试用的softmax函数
y_conv2=tf.nn.softmax(tf.matmul(h_fc1, W_fc2) + b_fc2,name="final_result")#交叉熵的计算,返回包含了损失值的Tensor。cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
#优化器,负责最小化交叉熵
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
#计算准确率
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)#训练开始
for i in range(1000):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()可以看做输入相关值给到函数中的占位符,然后计算的出结果,这里将batch[0],给xbatch[1]给y_train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})#将当前图设置为默认图
graph_def = tf.get_default_graph().as_graph_def()
#将上面的变量转化成常量,保存模型为pb模型时需要,注意这里的final_result和前面的y_con2是同名,只有这样才会保存它,否则会报错,
# 如果需要保存其他tensor只需要让tensor的名字和这里保持一直即可
output_graph_def = tf.graph_util.convert_variables_to_constants(sess,  graph_def, ['final_result'])
#保存前面训练后的模型为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")  ##导入图片,同时灰度化
#im = cv2.imread('pic/e2.jpg',cv2.IMREAD_GRAYSCALE)
##反转图像,因为e2.jpg为白底黑字
#im =reversePic(im)
#cv2.namedWindow("camera", cv2.WINDOW_NORMAL);
#cv2.imshow('camera',im)
#cv2.waitKey(0)
#
##调整大小
#im = cv2.resize(im,(28,28),interpolation=cv2.INTER_CUBIC)
#x_img = np.reshape(im , [-1 , 784])
#
#
##输出图像矩阵
## print x_img
#
##用上面导入的图片对模型进行测试
#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}))

加载模型第一种

# -*- coding:utf-8 -*-
import cv2
import tensorflow as tf
import numpy as np
from sys import path
#用于将自定义输入图片反转
def reversePic(src):# 图像反转  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()
#模型恢复saver=tf.train.import_meta_graph('model_data/model.meta')saver.restore(sess, 'model_data/model')graph = tf.get_default_graph()# 获取输入tensor,,获取输出tensorinput_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]path1="pic/e2.jpg"  im = cv2.imread(path1,cv2.IMREAD_GRAYSCALE)#反转图像,因为e2.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]#数据从0~255转为-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)) )#关闭会话  sess.close()  if __name__ == '__main__':  main()

加载模型第二种

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 17 11:15:53 2019@author: lg
"""#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#用于将自定义输入图片反转
def reversePic(src):# 图像反转  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) #反转图像,因为e2.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)) )#关闭会话  sess.close()

tensorflow加载模型相关推荐

  1. tensorflow 加载模型

    训练模型 import tensorflow as tf import numpy as np import matplotlib.pyplot as plt money=np.array([[109 ...

  2. Tensorflow加载模型(进阶版):如何利用预训练模型进行微调(fintuning)

    我们要使用别人已经训练好的模型,就必须将.ckpt文件中的参数加载进来.我们如何有选择的加载.ckpt文件中的参数呢.首先我们要查看.ckpt都保存了哪些参数: 上代码: import tensorf ...

  3. tensorflow 1.x Saver(保存与加载模型) 预测

    20201231 tensorflow 1.X 模型保存 https://blog.csdn.net/qq_35290785/article/details/89646248 保存模型 saver=t ...

  4. tensorflow tf.train.ExponentialMovingAverage().variables_to_restore()函数 (用于加载模型时将影子变量直接映射到变量本身)

    variables_to_restore函数,是TensorFlow为滑动平均值提供.之前,也介绍过通过使用滑动平均值可以让神经网络模型更加的健壮.我们也知道,其实在TensorFlow中,变量的滑动 ...

  5. tensorflow加载训练好的模型实例

    1. 首先了解下tensorflow的一些基础语法知识 这里不再详细说明其细节,只举例学习. 1.1 tensorflow的tf.transpose()简单使用: tf.reshape(tensor, ...

  6. TensorFlow 加载多个模型的方法

    采用 TensorFlow 的时候,有时候我们需要加载的不止是一个模型,那么如何加载多个模型呢? 原文:https://bretahajek.com/2017/04/importing-multipl ...

  7. Tensorflow学习(二)之——保存加载模型、Saver的用法

    1. Saver的背景介绍 我们经常在训练完一个模型之后希望保存训练的结果,这些结果指的是模型的参数,以便下次迭代的训练或者用作测试.Tensorflow针对这一需求提供了Saver类. Saver类 ...

  8. tensorflow中保存模型、加载模型做预测(不需要再定义网络结构)

    下面用一个线下回归模型来记载保存模型.加载模型做预测 参考文章: http://blog.csdn.net/thriving_fcl/article/details/71423039 训练一个线下回归 ...

  9. TensorFlow 加载多个模型的方法 - 知乎 https://zhuanlan.zhihu.com/p/53642222

    TensorFlow 加载多个模型的方法 - 知乎 什么是Tensorflow模型? 当你训练好一个神经网络后,你会想保存好你的模型便于以后使用并且用于生产.因此,什么是Tensorflow模型?Te ...

最新文章

  1. 织梦 百度sitemap制作教程
  2. 辞旧迎新,总结2010,展望2011
  3. JS与CSS阻止元素被选中及清除选中的方法总结
  4. spyder 崩溃解决方案
  5. 【五校联考6day2】san
  6. boost::iostreams::detail::execute_all用法的测试程序
  7. 关于java.math.BigDecimal的操作(亲测)
  8. loadrunner如何监控linux,以及重点指标分析
  9. 记一次ZABBIX监控JMX故障
  10. linux transmission,Linux下使用Transmission新版
  11. 安兔兔2月Android手机性价比榜出炉:Redmi包揽前三
  12. MyBatis 缓存原来是这么一回事儿!| 原力计划
  13. 冲击波病毒内幕点滴(4)
  14. 桌面壁纸被计算机管理员禁用,Win7更改桌面壁纸时出现“此功能已被禁用”如何解决...
  15. ClickHouse 创建数据库建表视图字典 SQL
  16. 飞秋教程(飞秋应用管理器)
  17. android 火车购票功能,12306 火车票订票
  18. 《哪来的天才》读书笔记
  19. log4j WARN 和 SLF4J WARN 解决办法
  20. scheme Android

热门文章

  1. 我思故我在之编程规范及编程思想篇
  2. Python中的test测试
  3. 网络设备主备配置系列3:华为防火墙(路由模式)
  4. Terraform 多云管理工具
  5. webpack文章(持续更新)
  6. CI框架 -- CLI执行php代码
  7. 深入浅出 JQuery (一) 浅析JQuery
  8. h3c telnet
  9. RedHat系统常用的日志文件详解三
  10. 值得研究的 开源数据库