首页 > 解决方案 > 如何使用 tensorflow 2.0 C API?

问题描述

我正在尝试在 Xcode 的 C++ 项目中使用 tensorflow。我已经按照他们的网页(https://www.tensorflow.org/install/lang_c)上的“Install TensorFlow for C”教程进行操作。

我必须更改 Xcode 项目的构建设置部分中的几个字段才能使其正常工作。

  1. 我在标题搜索路径中添加了“/usr/local/include”。
  2. 我在库搜索路径中添加了“/usr/local/lib”。
  3. 我在其他链接器标志中添加了“-ltensorflow”。

之后,程序正确编译并打印:“Hello from TensorFlow C library version 2.4.0”。所以按照教程,安装成功了,应该可以使用C API了。

我不明白的是如何访问 API 本身。例如,如何声明 tensorflow::Scope 类型的变量?

根据我在网上找到的其他教程(例如:https ://itnext.io/creating-a-tensorflow-dnn-in-c-part-1-54ce69bbd586 )我应该包含一个位于tensorflow/core/framework/...但我没有这样的文件我电脑上的文件。

Tensorflow 表示整个 API 都可以通过单个文件访问tensorflow/c/c_api.h。但是,我怎样才能做出类似的using namespace tensorflow;工作呢?

我已经在这个问题上苦苦挣扎了好几天,我真的希望有人能够帮助我。

标签: c++xcodetensorflow

解决方案


The example you provided (tensorflow::Scope) can be used with C++ and and not with tensorflow C API. For this kind of instructions, you need to build the tensorflow from source (I found this repo very helpful https://github.com/FloopCZ/tensorflow_cc).

In case you want to use C API then you can call all those functions that you find in c_api.h. For example, the following is my C++ file (hello_tf_cpp.cpp):

#include <iostream>
#include <tensorflow/c/c_api.h>

int main() {
  std::cout << "Hello from Tensorflow C++ library version " << TF_Version() << std::endl;
  //printf("Hello from TensorFlow C library version %s\n", TF_Version());

  TF_Graph* Graph = TF_NewGraph();
  TF_Status* Status = TF_NewStatus();
  TF_SessionOptions* SessionOpts = TF_NewSessionOptions();
  TF_Buffer* RunOpts = NULL;
  return 0;
}

And this is how I compile and run it:

$ g++ -I/usr/local/include -L /usr/local/lib hello_tf_cpp.cpp -l tensorflow -o hello_tf_cpp
    $ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib
    $./hello_tf_cpp

    $ unset LD_LIBRARY_PATH

And this is the output I get: Hello from Tensorflow C++ library version 1.15.0


推荐阅读