自行编译TensorFlow for C v2.0

概览:

下载官网最新版:

https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow-cpu-linux-x86_64-1.15.0.tar.gz

由于官网没有最新版TensorFlow for C v2.0 二进制包

所以:::::->

安装依赖bazel

bazel 官网

以ubuntu为例:https://docs.bazel.build/versions/master/install-ubuntu.html

下载源码

bazel test是下载依赖并编译,并且最好带上-j 5参数,5为CPU核心数的一半,否则可能会卡死。build对应打压缩包。

1
2
3
4
git clone --depth=1 -b r2.0 https://github.com/tensorflow/tensorflow.git
cd tensorflow
bazel test -j 5 --config opt //tensorflow/tools/lib_package:libtensorflow_test
bazel build --config opt //tensorflow/tools/lib_package:libtensorflow

压缩包位置:bazel-bin/tensorflow/tools/lib_package/libtensorflow.tar.gz

安装使用

安装

1
2
sudo mkdir /opt/tensorflow
sudo tar -zxvf bazel-bin/tensorflow/tools/lib_package/libtensorflow.tar.gz -C /opt/tensorflow

刷新ld

新建文件sudo subl /etc/ld.so.conf.d/tensorflow.conf

加入以下内容:/opt/tensorflow/lib ,保存退出。

更新动态链接库缓存.sudo ldconfig

验证

main.c

1
2
3
4
5
6
7
#include 
#include

int main() {
printf("Hello from TensorFlow C library version %s\n", TF_Version());
return 0;
}

CMakeLists.txt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
cmake_minimum_required(VERSION 3.2)
project(hello4tensorflow-c)


set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_SOURCE_DIR}/bin)

add_definitions("-Wl,-rpath,/opt/tensorflow/lib")
link_directories("/opt/tensorflow/lib")

include_directories("./" "/opt/tensorflow//include/")

add_executable(${PROJECT_NAME} "main.c")
target_link_libraries(${PROJECT_NAME} PRIVATE tensorflow)

golang示例,但不能用与tensorflow2,因为它依赖libtensorflow.so.1,而不是libtensorflow.so.2

main.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package main

import (
"fmt"

tf "github.com/tensorflow/tensorflow/tensorflow/go"
"github.com/tensorflow/tensorflow/tensorflow/go/op"
)

func main() {
// Construct a graph with an operation that produces a string constant.
s := op.NewScope()
c := op.Const(s, "Hello from TensorFlow version "+tf.Version())
graph, err := s.Finalize()
if err != nil {
panic(err)
}

// Execute the graph in a session.
sess, err := tf.NewSession(graph, nil)
if err != nil {
panic(err)
}
output, err := sess.Run(nil, []tf.Output{c}, nil)
if err != nil {
panic(err)
}
fmt.Println(output[0].Value())
}
------ 文章已经结束,谢谢你的阅读 ------
------ article has ended,thank you for reading ------
Thanks support Me

---------------- The End ----------------