tensorflow目前支持最好的语言仍是python,但大部分服务都用C++ or Java开发,通常采用动态连接库(.so)方式调用算法,所以tensorflow的c/c++ API仍是有必要熟悉下,并且通过本人测试,相同算法,c接口相比python速度更快。html
下面讲解如何让程序调用tensorflow c/c++库python
1.编译库linux
先在github上下载tensorflow源码,执行./configure先配置项目,而后按照这篇博客里写的利用bazel编译动态连接库,编译命令以下ios
C版本:c++
bazel build :libtensorflow.sogit
C++版本:github
bazel build :libtensorflow_cc.so算法
编译成功后,在bazel-bin/tensorflow/目录下会出现libtensorflow.so/libtensorflow_cc.so文件session
2.其余依赖测试
在使用tensorflow c/c++接口时,会有不少头文件依赖、protobuf版本依赖等问题
(1)tensorflow/contrib/makefile目录下,找到build_all_xxx.sh文件并执行,例如准备在linux上使用,就执行build_all_linux.sh文件,成功后会出现一个gen文件夹
(2)把tensorflow和bazel-genfiles文件夹下的头文件都抽取出来放在一个文件夹下面,或者经过cmake把这两个路径添加进include_directories中
(3)tensorflow/contrib/makefile/gen/protobuf/include,也就是(1)中生成的文件夹中的头文件,也须要抽取或者在cmake中包含在include_directories中
3.编写代码
随便编写一段使用tf的代码,例以下面:
#include <tensorflow/core/platform/env.h> #include <tensorflow/core/public/session.h> #include <iostream> using namespace std; using namespace tensorflow; int main() { Session* session; Status status = NewSession(SessionOptions(), &session); if (!status.ok()) { cout << status.ToString() << "\n"; return 1; } cout << "Session successfully created.\n"; }
4.生成可执行文件
把libtensorflow_cc.so文件放在lib文件夹下,代码放在src文件夹下,编写cmakelist.txt,具体文件结构以下:
CMakeLists.txt
/src
/lib
/include
/build
下面是一个例子:
cmake_minimum_required (VERSION 2.8.8) project (tf_example) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -std=c++11 -W") aux_source_directory(./src DIR_SRCS) link_directories(./lib) include_directories( path_to_tensorflow/tensorflow path_to_tensorflow/tensorflow/bazel-genfiles path_to_tensorflow/tensorflow/contrib/makefile/gen/protobuf/include ) add_executable(tf_test ${DIR_SRCS}) target_link_libraries(tf_example tensorflow_cc)
接下来执行命令:
cd build
cmake ..
make
会生成一个tf_test可执行文件,执行无误即大功告成