TF基础4
模型的存储与加载
TF的API提供了两种方式来存储和加载模型:
1.生成检查点文件,扩展名.ckpt,通过在tf.train.Saver()对象上调用Saver.save()生成。包含权重和其他在程序中定义的变量,不包含图结构。
2.生成图协议文件,扩展名.pb,用tf.train.write_graph()保存,只包含图形结构,不包含权重,然后使用tf.import_graph_def()来加载图形。
模型的存储与加载
(https://github.com/nlintz/TensorFlow-Tutorials/blob/master/10_save_restore_net.py)
加载数据及定义模型
#加载数据
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels
X = tf.placeholder("float", [None, 784])
Y = tf.placeholder("float", [None, 10])
#初始化权重参数
w_h = init_weights([784, 625])
w_h2 = init_weights([625, 625])
w_o = init_weights([625, 10])
#定义权重函数
def init_weights(shape):
return tf.Variable(tf.random_normal(shape, stddev=0.01))
#定义模型
def model(X, w_h, w_h2, w_o, p_keep_input, p_keep_hidden): # this network is the same as the previous one except with an extra hidden layer + dropout
#第一个全连接层
X = tf.nn.dropout(X, p_keep_input)
h = tf.nn.relu(tf.matmul(X, w_h))
h = tf.nn.dropout(h, p_keep_hidden)
#第一个全连接层
h2 = tf.nn.relu(tf.matmul(h, w_h2))
h2 = tf.nn.dropout(h2, p_keep_hidden)
return tf.matmul(h2, w_o)#输出预测值
生成网络模型,得到预测值,代码如下:
p_keep_input = tf.placeholder("float")
p_keep_hidden = tf.placeholder("float")
py_x = model(X, w_h, w_h2, w_o, p_keep_input, p_keep_hidden)
定义损失函数:
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y))
train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost)
predict_op = tf.argmax(py_x, 1)
训练模型及存储模型
首先定义一个存储路径:
ckpt_dir = "./ckpt_dir"
if not os.path.exists(ckpt_dir):
os.makedirs(ckpt_dir)
定义一个计数器,为训练轮数计数:
global_step = tf.Variable(0, name='global_step', trainable=False)
当定义完所有变量后,调用tf.train.Saver()来保存和提取变量:
# Call this after declaring all tf.Variables.
saver = tf.train.Saver()
# This variable won't be stored, since it is declared after tf.train.Saver()
non_storable_variable = tf.Variable(777)
训练模型并存储
with tf.Session() as sess:
# you need to initialize all variables
tf.global_variables_initializer().run()
start = global_step.eval() # get last global_step
print("Start from:", start)
for i in range(start, 100):
for start, end in zip(range(0, len(trX), 128), range(128, len(trX)+1, 128)):
sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end],
p_keep_input: 0.8, p_keep_hidden: 0.5})
global_step.assign(i).eval() # set and update(eval) global_step with index, i
saver.save(sess, ckpt_dir + "/model.ckpt", global_step=global_step)
加载模型
如果有训练好的模型变量文件,可以用saver.restore()来进行模型加载:
# Launch the graph in a session
with tf.Session() as sess:
# you need to initialize all variables
tf.global_variables_initializer().run()
ckpt = tf.train.get_checkpoint_state(ckpt_dir)
if ckpt and ckpt.model_checkpoint_path:
print(ckpt.model_checkpoint_path)
saver.restore(sess, ckpt.model_checkpoint_path) # restore all variables
图的存储与加载
当仅保存图模型时,才将图写入二进制文件中:
v=tf.Variable(0,name='my_variable')
sess=tf.Session()
tf.train.write_graph(sess.gaph_def,'/tmp/tfmodel','train.pbtxt')
当读取时,又从协议文件中读取出来:
with tf.Session() as_sess:
with gfile.FastGFile("/tem/tfmodel/train.pbtxt",'rb') as f:
graph_def=tf.GraphDef()
graph_def.ParseFromString(f.read())
_sess.grap.as_default()
tf.import_graph_def(graph_def,name='tfgraph')
队列和线程
队列
在TF中有两种队列,即FIFOQueue和RandomShuffleQueue.
FIFOQueue:创建一个先入先出队列
RandomShuffleQueue:创建一个随机队列
队列管理器
QueueRunner
线程和协调器
使用协调器(Coordinator)来管理线程。
加载数据
TF给出了3种方法:
1.预加载数据:在TensorFlow图中定义常量或变量来保存所有数据
2.填充数据feeding:Python产生数据,再把数据填充后端
3.从文件中读取数据:让队列管理器从文件中读取数据
预加载数据
缺点:当训练数据较大时,很消耗内存。
x1=tf.constant([2,3,4])
x2=tf.constant([2,1,4])
y=tf.add(x1,x2)
填充数据
使用sess.run()中的feed_dict参数,将Python产生的数据填充给后端。
#设计图
a1=tf.placeholder(tf.int16)
a2=tf.placeholder(tf.int16)
b=tf.add(x1,x2)
#用Python产生数据
li1=[2,3,4]
li2=[2,1,4]
#打开一个会话,将数据填充给后端
with tf.Session() as sess:
print(sess.run(b,feed_dict={a1:li1,a2:li2})
(https://www.tensorflow.org/guide/datasets#preloaded_data)
填充的方式也有数据量大、消耗内存等缺点。这时最好用第三种,从文件读取。
填充数据
从文件中读取数据分为两个步骤:
1.把样本数据写入TFRecords二进制文件
2.再从队列中读取
TF基础4的更多相关文章
- TF基础3
批标准化 批标准化(batch normalization,BN)是为了克服神经网络层数加深导致难以训练而诞生的.深度神经网络随着深度加深,收敛会越来越慢,会导致梯度弥散问题(vanishing gr ...
- TF基础2
1.常用API 1.图,操作和张量 tf.Graph,tf.Operation,tf.Tensor 2.可视化 TensorBoard 3.变量作用域 在TF中有两个作用域(scope),一个是nam ...
- ROS tf基础使用知识
博客参考:https://www.ncnynl.com/archives/201702/1306.html ROS与C++入门教程-tf-坐标变换 说明: 介绍在c++实现TF的坐标变换 概念: Co ...
- TF基础5
卷积神经网络CNN 卷积神经网络的权值共享的网络结构显著降低了模型的复杂度,减少了权值的数量. 神经网络的基本组成包括输入层.隐藏层和输出层. 卷积神经网络的特点在于隐藏层分为卷积层和池化层. pad ...
- ROS探索总结(十八)——重读tf
在之前的博客中,有讲解tf的相关内容,本篇博客重新整理了tf的介绍和学习内容,对tf的认识会更加系统. 1 tf简介 1.1 什么是tf tf是一个让用户随时间跟踪多个参考系的功能包,它使用一种树型数 ...
- [TF] Architecture - Computational Graphs
阅读笔记: 仅希望对底层有一定必要的感性认识,包括一些基本核心概念. Here只关注Graph相关,因为对编程有益. TF – Kernels模块部分参见:https://mp.weixin.qq.c ...
- tf
第2章 Tensorflow keras实战 2-0 写在课程之前 课程代码的Tensorflow版本 大部分代码是tensorflow2.0的 课程以tf.kerasAPI为主,因而部分代码可以在t ...
- Variables多种表达
Variables:TF基础数据之一,常用于变量的训练...重要性刚学TF就知道了 1.tf.Variable() tf.Variable(initial_value=None, trainable= ...
- [Tensorflow] Cookbook - The Tensorflow Way
本章介绍tf基础知识,主要包括cookbook的第一.二章节. 方针:先会用,后定制 Ref: TensorFlow 如何入门? Ref: 如何高效的学习 TensorFlow 代码? 顺便推荐该领域 ...
随机推荐
- Windows Server 2012安装.net framework3.5(转)
1.先下载WIN2012R2安装NET3.5的专用数据源 https://pan.baidu.com/s/1bqiUTyR 提取码h09k 并解压,比如解压到桌面,解压后的路径为C:\Users\Ad ...
- 研究发现:TLS1.3中的 TLS 对话恢复机制可以追踪用户
由于隐私浏览器技术的日渐成熟,网站越来越无法通过 Cookie 和网页浏览器特征来追踪用户,但道高一尺魔高一丈,现在这些网站会用 TLS 1.3 中的 TLS 对话恢复机制追踪用户. 你以为禁用浏览器 ...
- 10分钟 PySimpleGUI 图形界面入门
import PySimpleGUI as sg layout = [ [sg.Text('Enter a Number')], [sg.Input()], [sg.OK()] ] event,(nu ...
- 通过js 实现 向页面插入js代码并生效,和页面postMessage通讯
此文章针对已经搭建好jenkins和会使用iconfont图标库而写. 主要目标就是在不通过更改html文件,完成页面交互图标信息,因为美工最多可以上传代码并且自动发布,并不会在Html中加入我 ...
- 计蒜客 时间复杂度 (模拟) & 洛谷 P3952 时间复杂度
链接 : Here! 思路 : 这是一道大模拟, 区分好情况就没问题了 循环构成部分 : $F , x , i , j$ 和 $E$ , 需要注意的是 $i , j$, - 分析 $i, j$ 的情况 ...
- CodeForces-546D Soldier and Number Game 筛法+动态规划
题目链接:https://cn.vjudge.net/problem/CodeForces-546D 题意 抱歉,我给忘了,现在看题目又看不懂: P 思路 筛法+dp 话说这个函数应该是积性函数,然后 ...
- ansible --help 文档
> ansible --help Usage: ansible <host-pattern> [options] Define and run a single task 'play ...
- [LeetCode] 347. 前K个高频元素
python 版方法1:链表 class Solution(object): def topKFrequent(self, nums, k): """ :type num ...
- java+selenium+testNG+excel 实现 web 网页的自动化测试
webdriver的关键字从excel读取,这样测试人员只需要在excel中填写相关用例即可 前端微站和后台系统的用例可整合在同一excel中,这样可实现前端与后台的闭循环测试 除了一些基本的校验规则 ...
- 《编程导论(Java)·7.4.4 String对象问题》
String是Java API中使用频率第一的类,曾经在CSDN论坛上.至少每一个月都有相关的贴子,讨论==和equals(). 本节介绍这一部分的内容,也有一个重要更正. String文字在程序中被 ...