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应用,可以将其功能总结为:提供一套界面,帮助用户管理特定的数据.在这一过程中,不同类型的对象要各司其职:模型对象负责保存数据,视图对象负责显示数据,控制器对象负责在模型对象与视图 ...
随机推荐
- 使用go-template自定义kubectl get输出
kubectl get相关资源,默认输出为kubectl内置,一般我们也可以使用-o json或者-o yaml查看其完整的资源信息.但是很多时候,我们需要关心的信息并不全面,因此我们需要自定义输出的 ...
- UIPresentationController - iOS自定义模态弹出框
参考: https://developer.apple.com/library/archive/featuredarticles/ViewControllerPGforiPhoneOS/Definin ...
- uni-app编写小程序
今天项目还没有开始开发,网上看到了uni-app官网介绍可以一套代码,多端使用,感觉很厉害的样子,就做了个小程序页面试试. uni-app 使用 vue语法,小程序api,内嵌mpvue,使我们能够很 ...
- 关于bootstrap框架美化的实例教程(python)
经过上一章的内容,其实就页面层来说已结可以很轻松的实现功能了,但是很明显美观上还有很大的欠缺,现在有一些很好的前端css框架,如AmazeUI,腾讯的WeUI等等,这里推荐一个和flask集成很好的b ...
- 【Contest Hunter 5302】金字塔
[原题链接]传送门 [题解思路] 1.考虑如何将序列与树相对应,想到类似dfs序和欧拉序,同一个子树对应序列连续 2.暴力分子树过于复杂,考虑简化(划重点: 若当前区间为[l,r],考虑第一颗子树所在 ...
- 从Scratch到Python——python turtle 一种比pygame更加简洁的实现
从Scratch到Python--python turtle 一种比pygame更加简洁的实现 现在很多学校都开设了Scratch课程,学生可以利用Scratch创作丰富的作品,然而Scratch之后 ...
- 用JSON.stringify处理循环引用对象
通常,我们会用JSON.stringify把Javascript对象序列化成JSON格式,这在大多数情况下是够用的.但是,当你要转换的对象里存在循环引用时,问题就来了. js对象循环引用导致内存泄漏 ...
- 微信小程序外包 就找北京动软 专业承接微信小程序定制
很多人问为什么要开发微信小程序,微信小程序的“入口”在哪儿? 1.只有访问过的小程序,才会出现所谓的「入口」. 所有访问过得小程序都可以从微信首屏下面的「发现」点过去.(必须是最新版微信) 这个所谓的 ...
- 蚂蚁金服ATEC城市峰会上海举行,三大发布迎接金融科技2019
2019年1月4日,蚂蚁金服ATEC城市峰会以“数字金融新原力(The New Force of Digital Finance)”为主题在上海举办.稠州银行副行长程杰.蚂蚁金服副总裁刘伟光.蚂蚁金服 ...
- Asp.Net MVC 从客户端<a href="http://www....")中检测到有潜在危险的 Request.Form 值
Asp.Net MVC应用程序, Framework4.0: 则需要在webconfig文件的 <system.web> 配置节中加上 <httpRuntime requestVal ...