python - 从在 python 中创建的包含新操作的 pb 图在 c++ 中创建图

标签 python c++ tensorflow

如何将我的 libtensorflow_cc.so 库与我的自定义操作链接起来,以便我可以使用 C++ 进行训练?我的自定义操作是用 c++ 编写的,使用它的图形是用 python 计算的。我可以加载 pb 图表,但无法创建图表。

我在 python 中创建了一个图形并使用 write_graph 保存为一个 protobuf 文件。我的图表使用了一个自定义操作,其内核是用 C++ 编写的,并在 https://www.tensorflow.org/versions/master/extend/adding_an_op#compile_the_op_using_your_system_compiler_tensorflow_binary_installation 中注册。 .我想在 c++ 中加载我的图表进行训练,图表加载时没有警告,但对于“session->Create(graph_def)”我收到错误:

Non-OK-status: session->Create(graph_def) status: Not found: 
Op type not registered 'MyOp' in binary running on user-linux. 
Make sure the Op and Kernel are registered in the binary running in this process. 
Note that if you are loading a saved graph which used ops from tf.contrib,
accessing (e.g.) `tf.contrib.resampler` should be done before importing the graph,
as contrib ops are lazily registered when the module is first accessed.

我没有使用来自 tf.contrib 的任何东西。这是我的 C++ 代码的更简单版本:

    std::string graph_definition = "Mygraph.pb";
    Session* session; 
    GraphDef graph_def;
    SessionOptions opts;


    //load graph 
    TF_CHECK_OK(ReadBinaryProto(Env::Default(), graph_definition, &graph_def));
    // create a new session
    TF_CHECK_OK(NewSession(opts, &session));
    // Load graph into session
    TF_CHECK_OK(session->Create(graph_def)); 

最佳答案

看来您需要使用 c/c_api.h 中定义的 TF_LoadLibrary 加载您的库.在 c/c_api_test.cc你有一个它如何工作的例子:

// Load the library.
TF_Status* status = TF_NewStatus();
TF_Library* lib =
    TF_LoadLibrary("tensorflow/c/test_op.so", status);
TF_Code code = TF_GetCode(status);
string status_msg(TF_Message(status));
TF_DeleteStatus(status);
ASSERT_EQ(TF_OK, code) << status_msg;

该函数加载库并注册它在 TensorFlow 运行时中定义的操作和内核。


编辑:

好吧,从技术上讲,加载库的重要函数是 tensorflow::LoadLibrary,在 core/framework/load_library.cc 中定义.但是,此函数 1) 似乎并未在任何 header 中公开声明(实际上,c/c_api.cc 包含此函数的声明供内部使用)2) 具有相当模糊的参数。据我所知,C API 目前似乎是在 C++ 程序中加载库的更简单方法,即使您必须注意适当销毁对象(即调用 TF_DeleteLibraryHandle) .顺便说一句,似乎也没有卸载库的方法;您可以销毁库句柄对象,但这不会卸载库。

关于python - 从在 python 中创建的包含新操作的 pb 图在 c++ 中创建图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51392895/

相关文章:

c++ - 我这里的异常处理有什么问题?

C++ - 如何在另一个类中使用私有(private)构造函数实例化对象

python - Keras 输入层和 Tensorflow 占位符之间的区别

python - 聚类算法的编程结构

python - django 和 mod_wsgi 有数据库连接问题

python - MySql FetchMany 内存问题

c++ - 在 [a,b] 间隔之间找到相同的数字

python - 如何在 v1.13.1 中恢复 tensorflow v1.1.0 保存的模型

Tensorflow Lite GPU 对 python 的支持

python - 无法在 matplotlib : Windows permission denied 中保存动画