转自:http://blog.csdn.net/jmh1996/article/details/73197337?locationNum=6
前言
Tensorflow 网上大部分是python的资料较多,而C++方面的极少,因此,接下来会有一系列的博客用于学习tensorflow,记录学习的过程。加油!
搭建环境
既然使用C++的API,那第一步就是搭建Tensorflow的工作环境
1. 准备一台64位的虚拟机 ,我安装的ubuntu 16.04 64位的. 用新的虚拟机主要是图个干净利落,同时修改好软件源,建议改成阿里云的,安装一些常用的运行库,开发库。
2. 安装 bazel
> echo
"deb [arch=amd64] http://storage.googleapis.com/bazel-apt stable jdk1.8"
| sudo tee /etc/apt/sources
.list
.d
/bazel
.list
curl https://bazel
.build
/bazel-release
.pub
.gpg
| sudo apt-key
add
->sudo apt-get update && sudo apt-get install bazel
可能会提示没有安装curl,则需要先安装curl
> sudo apt-get install curl
安装bazel
>sudo apt-get update && sudo apt-get install bazel
本人使用 ubuntu 16.04刚上的虚拟机,妥妥的。
3. 安装python的一些常用库
>sudo apt-get install sudo apt-get install python-numpy python-dev python-pip python-wheel -y
- 安装cpu 开发工具库
>sudo apt-get install libcupti-dev
- 下载tensorflow 源码
>sudo apt-get install git
>git clone https://github.com/tensorflow/tensorflow
>cd tensorflow
>./configure
出现这个就配置对了:
INFO:All external dependencies fetched successfully.
- 安装tensorflow ,使用pip
> --
- 测试C++接口
将 tensorflow目录下的:tensorflow/cc/example/example.cc 文件内容替换为(没有就新建一个这个目录下的文件):
#include "tensorflow/cc/client/client_session.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/framework/tensor.h"
int main() {
using namespace tensorflow;
using namespace tensorflow::ops;
Scope root = Scope::NewRootScope();
auto A = Const(root, { {3.f, 2.f}, {-1.f, 0.f}});
auto b = Const(root, { {3.f, 5.f}});
auto v = MatMul(root.WithOpName("v"), A, b, MatMul::TransposeB(true));
std::vector<Tensor> outputs;
ClientSession session(root);
TF_CHECK_OK(session.Run({v}, &outputs));
std::cout<< outputs[0].matrix<float>();
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
在tensorflow/cc/example/ 目录下新建一个BUILD文件,文件内容:
cc_binary(
name = "example",
srcs = ["example.cc"],
deps = [
"//tensorflow/cc:cc_ops",
"//tensorflow/cc:client_session",
"//tensorflow/core:tensorflow",
],
)
编译:
>cd tensorflow
>bazel run -c opt //tensorflow/cc/example:example
然后首次编译很久,等一会儿就好。
最后打印出:
2017-06-13 17:20:50.578854: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-06-13 17:20:50.578970: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-06-13 17:20:50.578992: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
19
-3
说明安装成功。
但是!这里有太多的调试信息了,我们把它去掉:
>export TF_CPP_MIN_LOG_LEVEL=2
>bazel-bin/tensorflow/cc/example/example
打印:
19
-3
OK Perfect!