要将训练有素的网络导入C++,您需要导出网络才能这样做。经过大量搜索并且几乎没有找到有关它的信息之后,我们澄清了应该使用freeze_graph()来做到这一点。

感谢Tensorflow的新0.7版本,他们添加了documentation

查阅文档后,我发现几乎没有类似的方法,您能告诉我freeze_graph()和:
tf.train.export_meta_graph,因为它具有相似的参数,但似乎也可以用于将模型导入到C++中(我只是觉得区别在于,使用此方法输出的文件只能使用import_graph_def()或其他?)

还有一个有关如何使用write_graph()的问题:
在文档中graph_defsess.graph_def给出,但是在freeze_graph()的示例中,它是sess.graph.as_graph_def()。两者有什么区别?

这个问题与this issue.有关

谢谢!

最佳答案

这是我利用TF 0.12中引入的V2检查点的解决方案。

无需将所有变量都转换为常量或freeze the graph

为了清楚起见,V2检查点在我的目录models中如下所示:

checkpoint  # some information on the name of the files in the checkpoint
my-model.data-00000-of-00001  # the saved weights
my-model.index  # probably definition of data layout in the previous file
my-model.meta  # protobuf of the graph (nodes and topology info)

Python部分(保存)
with tf.Session() as sess:
    tf.train.Saver(tf.trainable_variables()).save(sess, 'models/my-model')

如果使用Saver创建tf.trainable_variables(),则可以节省一些头痛和存储空间。但是,也许某些更复杂的模型需要保存所有数据,然后将其删除到Saver,只需确保在创建了后创建了Saver 即可。为所有变量/层赋予唯一名称也是非常明智的,否则可以在different problems中运行。

Python部分(推断)
with tf.Session() as sess:
    saver = tf.train.import_meta_graph('models/my-model.meta')
    saver.restore(sess, tf.train.latest_checkpoint('models/'))
    outputTensors = sess.run(outputOps, feed_dict=feedDict)

C++部分(推论)

请注意,checkpointPath并不是任何现有文件的路径,只是它们的公共(public)前缀。如果您错误地在其中放置了.index文件的路径,则TF不会告诉您这是错误的,但是由于未初始化的变量,它会在推断期间死亡。
#include <tensorflow/core/public/session.h>
#include <tensorflow/core/protobuf/meta_graph.pb.h>

using namespace std;
using namespace tensorflow;

...
// set up your input paths
const string pathToGraph = "models/my-model.meta"
const string checkpointPath = "models/my-model";
...

auto session = NewSession(SessionOptions());
if (session == nullptr) {
    throw runtime_error("Could not create Tensorflow session.");
}

Status status;

// Read in the protobuf graph we exported
MetaGraphDef graph_def;
status = ReadBinaryProto(Env::Default(), pathToGraph, &graph_def);
if (!status.ok()) {
    throw runtime_error("Error reading graph definition from " + pathToGraph + ": " + status.ToString());
}

// Add the graph to the session
status = session->Create(graph_def.graph_def());
if (!status.ok()) {
    throw runtime_error("Error creating graph: " + status.ToString());
}

// Read weights from the saved checkpoint
Tensor checkpointPathTensor(DT_STRING, TensorShape());
checkpointPathTensor.scalar<std::string>()() = checkpointPath;
status = session->Run(
        {{ graph_def.saver_def().filename_tensor_name(), checkpointPathTensor },},
        {},
        {graph_def.saver_def().restore_op_name()},
        nullptr);
if (!status.ok()) {
    throw runtime_error("Error loading checkpoint from " + checkpointPath + ": " + status.ToString());
}

// and run the inference to your liking
auto feedDict = ...
auto outputOps = ...
std::vector<tensorflow::Tensor> outputTensors;
status = session->Run(feedDict, outputOps, {}, &outputTensors);

关于python - Tensorflow在C++中导出和运行图形的不同方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35508866/

10-11 23:00
查看更多