如何在C ++中保存和恢复TensorFlow图及其状态? [英] How to save and restore a TensorFlow graph and its state in C++?
问题描述
我正在使用C ++中的TensorFlow训练我的模型。 Python仅用于构造图形。那么,有没有一种方法可以仅使用C ++来保存和恢复图形及其状态?我知道Python类 tf.train.Saver
,但据我所知,它在C ++中不存在。
I'm training my model using TensorFlow in C++. Python is used only for constructing the graph. So is there a way to save and restore the graph and its state purely in C++? I know about the Python class tf.train.Saver
but as far as I understand it does not exist in C++.
推荐答案
tf.train.Saver
类当前仅在Python中存在,但但是(i)是从TensorFlow ops构建的,可以从C ++运行,并且(ii)公开 Saver.as_saver_def()
方法,该方法可让您获取 SaverDef
协议缓冲区,带有您所拥有的ops名称必须运行才能保存或还原模型。
The tf.train.Saver
class currently exists only in Python, but (i) it is built from TensorFlow ops that you can run from C++, and (ii) it exposes the Saver.as_saver_def()
method that lets you get a SaverDef
protocol buffer with the names of ops that you must run to save or restore a model.
在Python中,您可以按以下方式获取保存和还原操作的名称:
In Python, you can get the names of the save and restore ops as follows:
saver = tf.train.Saver(...)
saver_def = saver.as_saver_def()
# The name of the tensor you must feed with a filename when saving/restoring.
print saver_def.filename_tensor_name
# The name of the target operation you must run when restoring.
print saver_def.restore_op_name
# The name of the target operation you must run when saving.
print saver_def.save_tensor_name
在C ++中从检查点还原时,调用 Session :: Run()
,将检查点文件的名称输入为 saver_def.filename_tensor_name
,目标操作数为 saver_def.restore_op_name
。要保存另一个检查点,请调用 Session :: Run()
,再次将检查点文件的名称输入为 saver_def.filename_tensor_name
,并获取 saver_def.save_tensor_name
的值。
In C++ to restore from a checkpoint, you call Session::Run()
, feeding in the name of the checkpoint file as saver_def.filename_tensor_name
, with a target op of saver_def.restore_op_name
. To save another checkpoint, you call Session::Run()
, again feeding in the name of the checkpoint file as saver_def.filename_tensor_name
, and fetching the value of saver_def.save_tensor_name
.
这篇关于如何在C ++中保存和恢复TensorFlow图及其状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!