http://blog.csdn.net/huachao1001/article/details/78502910

http://blog.csdn.net/u014432647/article/details/75276718

https://zhuanlan.zhihu.com/p/32887066

#coding:utf-8
#http://blog.csdn.net/zhuiqiuk/article/details/53376283
#http://blog.csdn.net/gan_player/article/details/77586489
from __future__ import absolute_import, unicode_literals
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import shutil
import os.path
from tensorflow.python.framework import graph_util 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') def inference(input_image, keep_prob):
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
x_image = tf.reshape(input_image, [-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])
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")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10]) logits = tf.matmul(h_fc1_drop, W_fc2) + b_fc2 return logits def train(export_dir):
mnist = input_data.read_data_sets("datasets", one_hot=True) g = tf.Graph()
with g.as_default():
x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10])
keep_prob = tf.placeholder("float") logits = inference(x, keep_prob)
y_conv = tf.nn.softmax(logits) 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 = tf.Session()
sess.run(tf.initialize_all_variables()) for i in range(201):
batch = mnist.train.next_batch(50)
if i % 100 == 0:
train_accuracy = accuracy.eval(
{x: batch[0], y_: batch[1], keep_prob: 1.0}, sess)
print "step %d, training accuracy %g" % (i, train_accuracy)
train_step.run(
{x: batch[0], y_: batch[1], keep_prob: 0.5}, sess) print "test accuracy %g" % accuracy.eval(
{x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}, sess) saver = tf.train.Saver()
step = 200
checkpoint_file = os.path.join(export_dir, 'model.ckpt')
saver.save(sess, checkpoint_file, global_step=step)
checkpoint_file = os.path.join(export_dir, 'model.ckpt') def export_pb_model(model_name):
graph = tf.Graph()
with graph.as_default():
input_image = tf.placeholder("float", shape=[None,28*28], name='inputdata')
keep_prob = tf.placeholder("float", name = 'keep_probdata')
logits = inference(input_image, keep_prob)
y_conv = tf.nn.softmax(logits,name='outputdata')
restore_saver = tf.train.Saver() with tf.Session(graph=graph) as sess:
sess.run(tf.global_variables_initializer())
latest_ckpt = tf.train.latest_checkpoint('log')
restore_saver.restore(sess, latest_ckpt)
output_graph_def = tf.graph_util.convert_variables_to_constants(
sess, graph.as_graph_def(), ['outputdata']) # tf.train.write_graph(output_graph_def, 'log', model_name, as_text=False)
with tf.gfile.GFile(model_name, "wb") as f:
f.write(output_graph_def.SerializeToString()) def test_pb_model(model_name):
mnist = input_data.read_data_sets("datasets", one_hot=True) with tf.Graph().as_default():
output_graph_def = tf.GraphDef()
output_graph_path = model_name
# sess.graph.add_to_collection("input", mnist.test.images) with open(output_graph_path, "rb") as f:
output_graph_def.ParseFromString(f.read())
tf.import_graph_def(output_graph_def, name="") with tf.Session() as sess: tf.initialize_all_variables().run()
input_x = sess.graph.get_tensor_by_name("inputdata:0")
output = sess.graph.get_tensor_by_name("outputdata:0")
keep_prob = sess.graph.get_tensor_by_name("keep_probdata:0") y_conv_2 = sess.run(output,{input_x:mnist.test.images, keep_prob: 1.0})
print( "y_conv_2", y_conv_2) # Test trained model
#y__2 = tf.placeholder("float", [None, 10])
y__2 = mnist.test.labels
correct_prediction_2 = tf.equal(tf.argmax(y_conv_2, 1), tf.argmax(y__2, 1))
print ("correct_prediction_2", correct_prediction_2 )
accuracy_2 = tf.reduce_mean(tf.cast(correct_prediction_2, "float"))
print ("accuracy_2", accuracy_2) print ("check accuracy %g" % accuracy_2.eval()) if __name__ == '__main__':
export_dir = './log'
if os.path.exists(export_dir):
shutil.rmtree(export_dir)
#训练并保存模型ckpt
train(export_dir)
model_name = os.path.join(export_dir, 'mnist.pb')
#ckpt模型转换为pb模型
export_pb_model(model_name)
#测试pb模型
test_pb_model(model_name)

$ python mymain.py

#训练并保存模型ckpt

Extracting datasets/train-images-idx3-ubyte.gz
Extracting datasets/train-labels-idx1-ubyte.gz
Extracting datasets/t10k-images-idx3-ubyte.gz
Extracting datasets/t10k-labels-idx1-ubyte.gz
2018-03-19 18:11:27.046638: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA
2018-03-19 18:11:27.169530: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:892] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2018-03-19 18:11:27.170178: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1030] Found device 0 with properties:
name: GeForce GTX 1080 major: 6 minor: 1 memoryClockRate(GHz): 1.7335
pciBusID: 0000:01:00.0
totalMemory: 7.92GiB freeMemory: 5.51GiB
2018-03-19 18:11:27.170196: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1120] Creating TensorFlow device (/device:GPU:0) -> (device: 0, name: GeForce GTX 1080, pci bus id: 0000:01:00.0, compute capability: 6.1)
WARNING:tensorflow:From /usr/local/lib/python2.7/dist-packages/tensorflow/python/util/tf_should_use.py:107: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
Instructions for updating:
Use `tf.global_variables_initializer` instead.
step 0, training accuracy 0.08
step 100, training accuracy 0.86
step 200, training accuracy 0.96
2018-03-19 18:11:29.100338: W tensorflow/core/common_runtime/bfc_allocator.cc:217] Allocator (GPU_0_bfc) ran out of memory trying to allocate 3.32GiB. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory is available.
test accuracy 0.9137

#ckpt模型转换为pb模型

2018-03-19 18:11:30.655025: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1120] Creating TensorFlow device (/device:GPU:0) -> (device: 0, name: GeForce GTX 1080, pci bus id: 0000:01:00.0, compute capability: 6.1)
Converted 8 variables to const ops.

#测试pb模型

Extracting datasets/train-images-idx3-ubyte.gz
Extracting datasets/train-labels-idx1-ubyte.gz
Extracting datasets/t10k-images-idx3-ubyte.gz
Extracting datasets/t10k-labels-idx1-ubyte.gz
2018-03-19 18:11:32.419375: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1120] Creating TensorFlow device (/device:GPU:0) -> (device: 0, name: GeForce GTX 1080, pci bus id: 0000:01:00.0, compute capability: 6.1)
(u'y_conv_2', array([[ 3.83061661e-06, 2.25869144e-06, 6.98342774e-05, ...,
9.99720514e-01, 5.38732929e-05, 6.28733032e-05],
[ 1.85461645e-03, 3.86392418e-03, 9.55442667e-01, ...,
1.31935649e-05, 2.71034874e-02, 4.14738406e-06],
[ 2.61329369e-05, 9.94501710e-01, 1.34233199e-03, ...,
8.23311449e-04, 1.73626456e-03, 3.27934940e-05],
...,
[ 1.58834242e-04, 1.02327869e-03, 9.29224771e-04, ...,
9.04104114e-03, 1.03222862e-01, 1.16873145e-01],
[ 9.86627676e-03, 1.02333550e-03, 2.13368423e-03, ...,
2.72160349e-03, 3.91508579e-01, 4.37955791e-03],
[ 1.95508893e-03, 2.17417346e-06, 1.18497398e-03, ...,
5.04385412e-07, 3.14567442e-05, 4.29990359e-06]], dtype=float32))
(u'correct_prediction_2', <tf.Tensor 'Equal:0' shape=(10000,) dtype=bool>)
(u'accuracy_2', <tf.Tensor 'Mean:0' shape=() dtype=float32>)
check accuracy 0.9137

TensorFlow基础笔记(14) 网络模型的保存与恢复_mnist数据实例的更多相关文章

  1. TensorFlow基础笔记(0) 参考资源学习文档

    1 官方文档 https://www.tensorflow.org/api_docs/ 2 极客学院中文文档 http://www.tensorfly.cn/tfdoc/api_docs/python ...

  2. TensorFlow基础笔记(3) cifar10 分类学习

    TensorFlow基础笔记(3) cifar10 分类学习 CIFAR-10 is a common benchmark in machine learning for image recognit ...

  3. TensorFlow 训练好模型参数的保存和恢复代码

    TensorFlow 训练好模型参数的保存和恢复代码,之前就在想模型不应该每次要个结果都要重新训练一遍吧,应该训练一次就可以一直使用吧. TensorFlow 提供了 Saver 类,可以进行保存和恢 ...

  4. TensorFlow进阶(六)---模型保存与恢复、自定义命令行参数

    模型保存与恢复.自定义命令行参数. 在我们训练或者测试过程中,总会遇到需要保存训练完成的模型,然后从中恢复继续我们的测试或者其它使用.模型的保存和恢复也是通过tf.train.Saver类去实现,它主 ...

  5. TensorFlow基础笔记(1) 数据读取与保存

    https://zhuanlan.zhihu.com/p/27238630 WholeFileReader # 我们用一个具体的例子感受tensorflow中的数据读取.如图, # 假设我们在当前文件 ...

  6. TensorFlow基础笔记(11) conv2D函数

    #链接:http://www.jianshu.com/p/a70c1d931395 import tensorflow as tf import tensorflow.contrib.slim as ...

  7. TensorFlow基础笔记(8) TensorFlow简单人脸识别

    数据材料 这是一个小型的人脸数据库,一共有40个人,每个人有10张照片作为样本数据.这些图片都是黑白照片,意味着这些图片都只有灰度0-255,没有rgb三通道.于是我们需要对这张大图片切分成一个个的小 ...

  8. Tensorflow基础笔记

    1.Keras是一个由Python编写的开源人工神经网络库. 2.深度学习主要应用在三个大的方向,计算机视觉,自然语言处理,强化学习 3.计算机视觉主要有:图片识别,目标检测,语义分割,视频理解(行为 ...

  9. 黑马程序员_java基础笔记(14)...交通灯管理系统_编码思路及代码

    —————————— ASP.Net+Android+IOS开发..Net培训.期待与您交流! —————————— 1,面试题——交通灯管理系统 模拟实现十字路口的交通灯管理系统逻辑,具体需求如下: ...

随机推荐

  1. MFC改变对话框背景颜色

    原文链接: http://blog.sina.com.cn/s/blog_59955afc0100spjz.html 方法一:调用CWinApp类的成员函数SetDialogBkColor来实现. - ...

  2. 利用WGET下载文件,并保存到指定目录

    wget是Linux上一个非常不错的下载指令,也算是Linux工作者常用的指令之一 而这个指令我想在各大系统都预设有提供,包括了Ubuntu.Fedora等,而一般来说,要使用wget下载档案,只需要 ...

  3. CentOS配置本地yum源/阿里云yum源/163yuan源,并配置yum源的优先级

    一.用Centos镜像搭建本地yum源 由于安装centos后的默认yum源为centos的官方地址,所以在国内使用很慢甚至无法访问,所以一般的做法都是把默认的yum源替换成aliyun的yum源或者 ...

  4. shell教程一:字符串操作

    一:Linux shell字符串截取与拼接 假设有变量 var=http://www.linuxidc.com/123.htm 1  # 号截取,删除左边字符,保留右边字符. echo ${var#* ...

  5. Oracle学习笔记之八(几条简明的优化SQL方法)

    1. 常规SQL语句优化 1.1 建议不用“*”来代替所有列名 SELECT语句中可以用“*“来列出某个表的所有列名,但是这样的写法对Oracle系统来说会存在解析的动态问题.Oracle系统会通过查 ...

  6. MySQL获取刚插入的数据

    1. 通过自增的键auto_increment取得. select max(id) from tablename 这样的做法须要考虑并发的情况.须要在事务中对主表加以"X锁",待获 ...

  7. Android Things专题2 硬件介绍

    文| 谷歌开发人员技术专家, 物联网方向 (IOT GDE) 王玉成(York Wang) 经过2016年Brillo首批开发人员的反馈,以及市场调研,为了照应广大Android开发人员的习惯,形成了 ...

  8. XILINX之RAM使用指南(加个人总结)

    先加点自己的总结:真双口RAM可以在任意时间访问任意地址,两个端口的地址是一样的,即共享内存和地址.这就会带来一个问题:同时读写一个地址会发生冲突.基于这个点矛盾就要设置限制条件,这个在Xilinx ...

  9. Calendar.NET

      Please Sign up or sign in to vote.请注册或登录投票. Download Binaries 下载二进制文件 Download source 下载源代码 Introd ...

  10. C++ 11 创建和使用 shared_ptr

    shared_ptr 的类型是C + +标准库中一个聪明的指针,是为多个拥有者管理内存中对象的生命周期而设计的.在你初始化一个 shared_ptr 后,你可以复制它,把函数参数的值递给它,并把它分配 ...