import tensorflow as tf
#Prepare to feed input, i.e. feed_dict and placeholders
w1 = tf.placeholder("float", name="w1")
w2 = tf.placeholder("float", name="w2")
b1= tf.Variable(2.0,name="bias")
feed_dict ={w1:4,w2:8}
#Define a test operation that we will restore
w3 = tf.add(w1,w2)
w4 = tf.multiply(w3,b1,name="op_to_restore")
sess = tf.Session()
sess.run(tf.global_variables_initializer())
#Create a saver object which will save all the variables
saver = tf.train.Saver()
#Run the operation by feeding input
print sess.run(w4,feed_dict)
#Prints 24 which is sum of (w1+w2)*b1
#Now, save the graph
saver.save(sess, 'my_test_model',global_step=1000)
Restore the model:
import tensorflow as tf
sess=tf.Session()
#First let's load meta graph and restore weights
saver = tf.train.import_meta_graph('my_test_model-1000.meta')
saver.restore(sess,tf.train.latest_checkpoint('./'))
# Access saved Variables directly
print(sess.run('bias:0'))
# This will print 2, which is the value of bias that we saved
# Now, let's access and create placeholders variables and
# create feed-dict to feed new data
graph = tf.get_default_graph()
w1 = graph.get_tensor_by_name("w1:0")
w2 = graph.get_tensor_by_name("w2:0")
feed_dict ={w1:13.0,w2:17.0}
#Now, access the op that you want to run.
op_to_restore = graph.get_tensor_by_name("op_to_restore:0")
print sess.run(op_to_restore,feed_dict)
#This will print 60 which is calculated
x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
w = tf.Variable(tf.zeros([1, 1], dtype=tf.float32))
b = tf.Variable(tf.ones([1, 1], dtype=tf.float32))
y_hat = tf.add(b, tf.matmul(x, w))
...more setup for optimization and what not...
saver = tf.train.Saver() # defaults to saving all variables - in this case w and b
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
if FLAGS.train:
for i in xrange(FLAGS.training_steps):
...training loop...
if (i + 1) % FLAGS.checkpoint_steps == 0:
saver.save(sess, FLAGS.checkpoint_dir + 'model.ckpt',
global_step=i+1)
else:
# Here's where you're restoring the variables w and b.
# Note that the graph is exactly as it was when the variables were
# saved in a prior training run.
ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess, ckpt.model_checkpoint_path)
else:
...no checkpoint found...
# Now you can run the model to get predictions
batch_x = ...load some data...
predictions = sess.run(y_hat, feed_dict={x: batch_x})
model_saver = tf.train.Saver()
# Train the model and save it in the end
model_saver.save(session, "saved_models/CNN_New.ckpt")
步骤3:恢复模型
with tf.Session(graph=graph_cnn) as session:
model_saver.restore(session, "saved_models/CNN_New.ckpt")
print("Model restored.")
print('Initialized')
第4步:检查你的变量
W1 = session.run(W1)
print(W1)
在不同的python实例中运行时,请使用
with tf.Session() as sess:
# Restore latest checkpoint
saver.restore(sess, tf.train.latest_checkpoint('saved_model/.'))
# Initalize the variables
sess.run(tf.global_variables_initializer())
# Get default graph (supply your custom graph if you have one)
graph = tf.get_default_graph()
# It will give tensor object
W1 = graph.get_tensor_by_name('W1:0')
# To get the value (numpy array)
W1_value = session.run(W1)
172
在大多数情况下,使用 tf.train.Saver 从磁盘保存和恢复是最佳选择:
... # build your model
saver = tf.train.Saver()
with tf.Session() as sess:
... # train the model
saver.save(sess, "/tmp/my_great_model")
with tf.Session() as sess:
saver.restore(sess, "/tmp/my_great_model")
... # use the model
saver = tf.train.import_meta_graph("/tmp/my_great_model.meta")
with tf.Session() as sess:
saver.restore(sess, "/tmp/my_great_model")
... # use the model
... # build your model
# get a handle on the graph nodes we need to save/restore the model
graph = tf.get_default_graph()
gvars = graph.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)
assign_ops = [graph.get_operation_by_name(v.op.name + "/Assign") for v in gvars]
init_values = [assign_op.inputs[1] for assign_op in assign_ops]
with tf.Session() as sess:
... # train the model
# when needed, save the model state to memory
gvars_state = sess.run(gvars)
# when needed, restore the model state
feed_dict = {init_value: val
for init_value, val in zip(init_values, gvars_state)}
sess.run(assign_ops, feed_dict=feed_dict)
graph = ... # build the graph
saver = tf.train.Saver() # create the saver after the graph
with ... as sess: # your session object
saver.save(sess, 'my-model')
正在加载
graph = ... # build the graph
saver = tf.train.Saver() # create the saver after the graph
with ... as sess: # your session object
saver.restore(sess, tf.train.latest_checkpoint('./'))
# now you can use the graph, continue training or whatever
也从文件中加载图表
When using this technique, make sure all your layers/variables have explicitly set unique names. 否则Tensorflow将使名称本身唯一,并且它们在前一种技术中不是问题,因为在加载和保存时名称都是"mangled"相同 .
保存
graph = ... # build the graph
for op in [ ... ]: # operators you want to use after restoring the model
tf.add_to_collection('ops_to_restore', op)
saver = tf.train.Saver() # create the saver after the graph
with ... as sess: # your session object
saver.save(sess, 'my-model')
正在加载
with ... as sess: # your session object
saver = tf.train.import_meta_graph('my-model.meta')
saver.restore(sess, tf.train.latest_checkpoint('./'))
ops = tf.get_collection('ops_to_restore') # here are your operators in the same order in which you saved them to the collection
# Some graph defined up here with specific names
saver = tf.train.Saver()
save_file = 'model.ckpt'
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
saver.save(sess, save_file)
但是为了恢复图形,您可能需要在文件名前加上“./”:
# Same graph defined up here
saver = tf.train.Saver()
save_file = './' + 'model.ckpt' # String addition used for emphasis
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
saver.restore(sess, save_file)
18 回答
新的和更短的方式:simple_save
许多好的答案,为了完整性,我将加上我的2美分: simple_save . 也是使用
tf.data.Dataset
API的独立代码示例 .Python 3; Tensorflow 1.7
恢复:
独立示例
Original blog post
以下代码为演示生成随机数据 .
我们首先创建占位符 . 他们将在运行时保存数据 . 从他们,我们创建
Dataset
然后它Iterator
. 我们得到迭代器生成的张量,称为input_tensor
,它将作为我们模型的输入 .模型本身是由
input_tensor
构建的:基于GRU的双向RNN,后跟密集分类器 . 因为为什么不呢 .损失是
softmax_cross_entropy_with_logits
,使用Adam
优化 . 经过2个时期(每个2批),我们用tf.saved_model.simple_save
保存"trained"模型 . 如果按原样运行代码,则模型将保存在当前工作目录中名为simple/
的文件夹中 .在新图表中,我们使用
tf.saved_model.loader.load
恢复保存的模型 . 我们使用graph.get_tensor_by_name
获取占位符和logits,使用graph.get_operation_by_name
获取Iterator
初始化操作 .最后,我们对数据集中的两个批次进行推断,并检查保存和恢复的模型是否都产生相同的值 . 他们是这样!
码:
这将打印:
我正在改进我的答案,添加更多有关保存和恢复模型的详细信息 .
在(及之后) Tensorflow version 0.11 :
Save the model:
Restore the model:
这里和一些更高级的用例已经在这里得到了很好的解释 .
A quick complete tutorial to save and restore Tensorflow models
在(及之后)TensorFlow版本0.11.0RC1中,您可以根据https://www.tensorflow.org/programmers_guide/meta_graph调用
tf.train.export_meta_graph
和tf.train.import_meta_graph
来直接保存和恢复模型 .保存模型
恢复模型
对于TensorFlow版本<0.11.0RC1:
保存的检查点包含模型中
Variable
的值,而不是模型/图形本身,这意味着恢复检查点时图形应该相同 .以下是线性回归的示例,其中有一个训练循环可以保存变量检查点,还有一个评估部分可以恢复先前运行中保存的变量并计算预测 . 当然,如果您愿意,还可以恢复变量并继续训练 .
以下是
Variable
的docs,其中包括保存和恢复 . 以下是Saver
的docs .我的环境:Python 3.6,Tensorflow 1.3.0
虽然有很多解决方案,但大多数都基于
tf.train.Saver
. 当我们加载由Saver
保存的.ckpt
时,我们必须重新定义张量流网络或使用一些奇怪且难以记住的名称,例如'placehold_0:0'
,'dense/Adam/Weight:0'
. 在这里,我建议使用tf.saved_model
,下面给出一个最简单的示例,您可以从Serving a TensorFlow Model了解更多信息:Save the model:
Load the model:
模型有两个部分,模型定义,由模型目录中的
Supervisor
保存为graph.pbtxt
,张量的数值保存到检查点文件中,如model.ckpt-1003418
.可以使用
tf.import_graph_def
恢复模型定义,并使用Saver
恢复权重 .但是,
Saver
使用特殊的集合保存变量列表,这些变量目前使用这两个变量(它在我们的路线图中进行修复) . 目前,您必须使用Ryan Sepassi的方法 - 手动构建具有相同节点名称的图形,并使用Saver
将权重加载到其中 .(或者你可以通过使用
import_graph_def
,手动创建变量,并为每个变量使用tf.add_to_collection(tf.GraphKeys.VARIABLES, variable)
,然后使用Saver
来破解它)你也可以采取这种更简单的方式 .
步骤1:初始化所有变量
步骤2:将会话保存在模型保护程序中并保存
步骤3:恢复模型
第4步:检查你的变量
在不同的python实例中运行时,请使用
在大多数情况下,使用
tf.train.Saver
从磁盘保存和恢复是最佳选择:您还可以保存/恢复图形结构本身(有关详细信息,请参阅MetaGraph documentation) . 默认情况下,
Saver
将图形结构保存到.meta
文件中 . 您可以调用import_meta_graph()
来恢复它 . 它恢复图形结构并返回一个Saver
,您可以使用它来恢复模型的状态:但是,有些情况下你需要更快的东西 . 例如,如果您实施提前停止,则希望每次模型在训练期间改进时保存检查点(在验证集上测量),然后如果一段时间没有进展,则需要回滚到最佳模型 . 如果你保存每次改进模型到磁盘,它将极大地减慢培训速度 . 诀窍是将变量状态保存到内存,然后稍后恢复它们:
快速解释:当您创建变量
X
时,TensorFlow会自动创建赋值操作X/Assign
以设置变量的初始值 . 我们只使用这些现有的赋值操作,而不是创建占位符和额外的赋值操作(这会使图形变得混乱) . 每个赋值op的第一个输入是对它应该初始化的变量的引用,第二个输入(assign_op.inputs[1]
)是初始值 . 因此,为了设置我们想要的任何值(而不是初始值),我们需要使用feed_dict
并替换初始值 . 是的,TensorFlow允许您为任何操作提供值,而不仅仅是占位符,所以这很好 .正如Yaroslav所说,你可以通过导入图形,手动创建变量,然后使用Saver来修复graph_def和checkpoint .
我实现了这个用于个人用途,所以我虽然在这里分享代码 .
链接:https://gist.github.com/nikitakit/6ef3b72be67b86cb7868
(当然,这是一个黑客攻击,并且无法保证以这种方式保存的模型在未来的TensorFlow版本中仍然可读 . )
如果它是内部保存的模型,则只需为所有变量指定恢复器
并使用它来恢复当前会话中的变量:
对于外部模型,您需要指定从其变量名到变量名的映射 . 您可以使用该命令查看模型变量名称
inspect_checkpoint.py脚本可以在Tensorflow源的“./tensorflow/python/tools”文件夹中找到 .
要指定映射,可以使用我的Tensorflow-Worklab,它包含一组类和脚本来训练和重新训练不同的模型 . 它包括一个重新训练ResNet模型的例子,位于here
这是我对两个基本情况的简单解决方案,这两个基本情况不同于您是要从文件加载图还是在运行时构建它 .
这个答案适用于Tensorflow 0.12(包括1.0) .
在代码中重建图形
保存
正在加载
也从文件中加载图表
When using this technique, make sure all your layers/variables have explicitly set unique names. 否则Tensorflow将使名称本身唯一,并且它们在前一种技术中不是问题,因为在加载和保存时名称都是"mangled"相同 .
保存
正在加载
您还可以在TensorFlow/skflow中查看examples,它提供了
save
和restore
方法,可以帮助您轻松管理模型 . 它具有参数,您还可以控制备份模型的频率 .如果您使用tf.train.MonitoredTrainingSession作为默认会话,那么您将使用会话挂钩来处理这些问题 .
如问题_866036中所述:
代替
这里的所有答案都很棒,但我想添加两件事 .
首先,要详细说明@ user7505159的答案,“./”对于添加到要还原的文件名的开头非常重要 .
例如,您可以在文件名中保存没有“./”的图形,如下所示:
但是为了恢复图形,您可能需要在文件名前加上“./”:
您不会总是需要“./”,但它可能会导致问题,具体取决于您的环境和TensorFlow版本 .
它还想提一下,在恢复会话之前,
sess.run(tf.global_variables_initializer())
可能很重要 .如果在尝试还原已保存的会话时收到有关未初始化变量的错误,请确保在
saver.restore(sess, save_file)
行之前包含sess.run(tf.global_variables_initializer())
. 它可以让你头疼 .如果要减小模型大小,请使用tf.train.Saver保存模型,remerber,需要指定var_list . val_list可以是tf.trainable_variables或tf.global_variables .
根据新的Tensorflow版本,
tf.train.Checkpoint
是保存和恢复模型的首选方式:这是一个例子:
More information and example here.
渴望模式也是一个未解决的保存/恢复问题,尽管文档肯定会回答,但没有人回答甚至文档都没有 . 这是我编写的非工作代码,它试图将tensorflow.contrib.eager中的Saver类用作tfe . 我的代码肯定保存到了磁盘...保存了一些东西 . 问题是恢复 . 我甚至添加了显式代码,首先手动重新创建所有内容,然后加载学习的参数:
它恢复了一些然后抛出一个ValueError: