tensorflow:保存与读取网络结构,参数
训练一个神经网络的目的是啥?不就是有朝一日让它有用武之地吗?可是,在别处使用训练好的网络,得先把网络的参数(就是那些variables)保存下来,怎么保存呢?其实,tensorflow已经给我们提供了很方便的API,来帮助我们实现训练参数的存储与读取,如果想了解详情,请看晦涩难懂的官方API,接下来我简单介绍一下我的理解。
保存与读取数据全靠下面这个类实现:
class tf.train.Saver
当我们需要存储数据时,下面2条指令就够了
saver = tf.train.Saver()
save_path = saver.save(sess, model_path)
然后怎么读取数据呢?看下面
saver = tf.train.Saver()
load_path = saver.restore(sess, model_path)
和存储数据神似啊!不再赘述。
下面是重点!关于tf.train.Saver()使用的几点小心得!
- 1、save方法在实现数据读取时,它仅仅读数据,关键是得有一些提前声明好的variables来接受这些数据,因此,当save读取数据到sess时,需要提前声明与数据匹配的variables,否则程序就报错了。
- 2、save读取的数据不需要initialize。
- 3、目前想到的就这么多,随时补充。
为了对数据存储和读取有更直观的认识,我自己写了两个实验小程序,下面是第一个,训练网络并存储数据,用的MNIST数据集
import tensorflow as tf
import sys # load MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('data', one_hot=True) # 一些 hyper parameters
activation = tf.nn.relu
batch_size = 100
iteration = 20000
hidden1_units = 30
# 注意!这里是存储路径!
model_path = sys.path[0] + '/simple_mnist.ckpt' X = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder(tf.float32, [None, 10]) W_fc1 = tf.Variable(tf.truncated_normal([784, hidden1_units], stddev=0.2))
b_fc1 = tf.Variable(tf.zeros([hidden1_units]))
W_fc2 = tf.Variable(tf.truncated_normal([hidden1_units, 10], stddev=0.2))
b_fc2 = tf.Variable(tf.zeros([10])) def inference(img):
fc1 = activation(tf.nn.bias_add(tf.matmul(img, W_fc1), b_fc1))
logits = tf.nn.bias_add(tf.matmul(fc1, W_fc2), b_fc2)
return logits def loss(logits, labels):
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits, labels)
loss = tf.reduce_mean(cross_entropy)
return loss def evaluation(logits, labels):
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
return accuracy logits = inference(X)
loss = loss(logits, y_)
train_op = tf.train.AdamOptimizer(1e-4).minimize(loss)
accuracy = evaluation(logits, y_) # 先实例化一个Saver()类
saver = tf.train.Saver()
init = tf.initialize_all_variables() with tf.Session() as sess:
sess.run(init)
for i in xrange(iteration):
batch = mnist.train.next_batch(batch_size)
if i%1000 == 0 and i:
train_accuracy = sess.run(accuracy, feed_dict={X: batch[0], y_: batch[1]})
print "step %d, train accuracy %g" %(i, train_accuracy)
sess.run(train_op, feed_dict={X: batch[0], y_: batch[1]})
print '[+] Test accuracy is %f' % sess.run(accuracy, feed_dict={X: mnist.test.images, y_: mnist.test.labels})
# 存储训练好的variables
save_path = saver.save(sess, model_path)
print "[+] Model saved in file: %s" % save_path
接下来是读取数据并做测试!
import tensorflow as tf
import sys from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('data', one_hot=True) activation = tf.nn.relu
hidden1_units = 30
model_path = sys.path[0] + '/simple_mnist.ckpt' X = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder(tf.float32, [None, 10]) W_fc1 = tf.Variable(tf.truncated_normal([784, hidden1_units], stddev=0.2))
b_fc1 = tf.Variable(tf.zeros([hidden1_units]))
W_fc2 = tf.Variable(tf.truncated_normal([hidden1_units, 10], stddev=0.2))
b_fc2 = tf.Variable(tf.zeros([10])) def inference(img):
fc1 = activation(tf.nn.bias_add(tf.matmul(img, W_fc1), b_fc1))
logits = tf.nn.bias_add(tf.matmul(fc1, W_fc2), b_fc2)
return logits def evaluation(logits, labels):
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
return accuracy logits = inference(X)
accuracy = evaluation(logits, y_) saver = tf.train.Saver() with tf.Session() as sess:
# 读取之前训练好的数据
load_path = saver.restore(sess, model_path)
print "[+] Model restored from %s" % load_path
print '[+] Test accuracy is %f' % sess.run(accuracy, feed_dict={X: mnist.test.images, y_: mnist.test.labels})
转:https://www.jianshu.com/p/83fa3aa2d0e9
tensorflow:保存与读取网络结构,参数的更多相关文章
- TensorFlow学习笔记(8)--网络模型的保存和读取【转】
转自:http://blog.csdn.net/lwplwf/article/details/62419087 之前的笔记里实现了softmax回归分类.简单的含有一个隐层的神经网络.卷积神经网络等等 ...
- 学习TensorFlow,TensorBoard可视化网络结构和参数
在学习深度网络框架的过程中,我们发现一个问题,就是如何输出各层网络参数,用于更好地理解,调试和优化网络?针对这个问题,TensorFlow开发了一个特别有用的可视化工具包:TensorBoard,既可 ...
- TensorFlow学习笔记:保存和读取模型
TensorFlow 更新频率实在太快,从 1.0 版本正式发布后,很多 API 接口就发生了改变.今天用 TF 训练了一个 CNN 模型,结果在保存模型的时候居然遇到各种问题.Google 搜出来的 ...
- Tensorflow实现LeNet-5、Saver保存与读取
一. LeNet-5 LeNet-5是一种用于手写体字符识别的非常高效的卷积神经网络. 卷积神经网络能够很好的利用图像的结构信息. 卷积层的参数较少,这也是由卷积层的主要特性即局部连接和共享权重所决定 ...
- Sklearn,TensorFlow,keras模型保存与读取
一.sklearn模型保存与读取 1.保存 from sklearn.externals import joblib from sklearn import svm X = [[0, 0], [1, ...
- Tensorflow保存神经网络参数有妙招:Saver和Restore
摘要:这篇文章将讲解TensorFlow如何保存变量和神经网络参数,通过Saver保存神经网络,再通过Restore调用训练好的神经网络. 本文分享自华为云社区<[Python人工智能] 十一. ...
- 10 Tensorflow模型保存与读取
我们的模型训练出来想给别人用,或者是我今天训练不完,明天想接着训练,怎么办?这就需要模型的保存与读取.看代码: import tensorflow as tf import numpy as np i ...
- Tensorflow创建和读取17flowers数据集
http://blog.csdn.net/sinat_16823063/article/details/53946549 Tensorflow创建和读取17flowers数据集 标签: tensorf ...
- iOS 保存、读取与应用状态
固化 对于大多数iOS应用,可以将其功能总结为:提供一套界面,帮助用户管理特定的数据.在这一过程中,不同类型的对象要各司其职:模型对象负责保存数据,视图对象负责显示数据,控制器对象负责在模型对象与视图 ...
随机推荐
- redis恢复(aof)
----------------redis备份恢复方法-----------------------------1.采用aof恢复方法若appendonly设置为no的情况下,在每个节点上执行bgre ...
- 关于py的思考
1.我希望py课程应该涉及到如何提高编程效率,因为已经c的编程基础,不是特别在意怎么用py,而是在意怎么用得更好 2.基本技能的话,掌握好各类基本函数的用法 3.理论课精讲,实验课独立操作,并把出现的 ...
- vue-cli 使用 webpack-bundle-analyzer
# build for production and view the bundle analyzer report npm run build --report
- PageRank算法实现
基本原理 在互联网上,如果一个网页被很多其他网页所链接,说明它受到普遍的承认和信赖,那么它的排名就高.这就是PageRank的核心思想. 引用来自<数学之美>的简单例子: 网页Y的排名应该 ...
- Kotlin 对象表达式和对象声明
Kotlin 用对象表达式和对象声明来实现创建一个对某个类做了轻微改动的类的对象,且不需要去声明一个新的子类. 对象表达式 通过对象表达式实现一个匿名内部类的对象用于方法的参数中: window.ad ...
- c#异步学习笔记
如下代码.只需要异步的处理一个数据,不需要等处理完成后,进行后继的操作.可以不用Async来修饰方法 static void Main(string[] args) { Test(); Console ...
- Axure中继器的应用场景和结构组成
应用场景: 当点击回复的时候,页面会会跳出来头像.昵称.时间.评论的内容(详情:https://jingyan.baidu.com/article/77b8dc7fb478346174eab622.h ...
- NetSec2019 20165327 Exp4 恶意代码分析
NetSec2019 20165327 Exp4 恶意代码分析 一.实践目标 1.监控你自己系统的运行状态,看有没有可疑的程序在运行. 2.分析一个恶意软件,就分析Exp2或Exp3中生成后门软件:分 ...
- 使用querybuilder做忽略大小写查询的例子
自定义Predicate: import com.day.cq.search.Predicate; import com.day.cq.search.eval.AbstractPredicateEva ...
- WARING
每一道题都先手玩样例! 认真读一下每一档数据,仔细计算每一档可以拿的分数! 读完题目后,把所有能想到的思路写在纸上. 最优化题目考虑dp和贪心两种方法 字符串题目前缀考虑trie树,后缀考虑fail树 ...