TensorFlow C++ API的使用

本文介绍如何使用TensorFlow构造计算图,包括创建图、定义操作函数、构造常量及执行图的过程。通过具体示例展示了MatMul、Add等操作的使用方法,以及如何构造不同类型的常量。

1. 构造图

Scope root = Scope::NewRootScope(); #构造一张新图,会创建一些资源

2.构造操作函数

auto m = MatMul(scope, a, b); //第一个参数始终是 Scope 对象,其余参数是张量输入和必需属性。

系统会以不同方式处理操作的参数和返回值,具体取决于操作的类型:

  • 对于返回单个张量的操作,操作对象返回的对象可以直接传递给其他操作构造函数。
    auto m = MatMul(scope, x, W);
    auto sum = Add(scope, m, bias);
    
  • 对于生成多个输出的操作,操作构造函数返回的对象具有与每个输出对应的一个成员。这些成员的名称与操作的 OpDef 中存在的名称相同
    auto u = Unique(scope, a);
    // u.y has the unique values and u.idx has the unique indices
    auto m = Add(scope, u.y, b);
    
  • 生成列表类型输出的操作会返回可以使用 [] 操作符编制索引的对象。该对象也可以直接传递给需要列表类型输入的其他构造函数。例如:
    auto s = Split(scope, 0, a, 2);
    // Access elements of the returned list.
    auto b = Add(scope, s[0], s[1]);
    // Pass the list as a whole to other constructors.
    auto c = Concat(scope, s, 0);
    

3. 构造常量

  • 标量
    auto f = Const(scope, 42.0f);
    auto s = Const(scope, "hello world!");	
    
  • 嵌套初始化列表
    // 2x2 matrix
    auto c1 = Const(scope, { {1, 2}, {2, 4} });
    // 1x3x1 tensor
    auto c2 = Const(scope, { { {1}, {2}, {3} } });
    // 1x2x0 tensor
    auto c3 = ops::Const(scope, { { {}, {} } });
    
  • 明确指定的形状
    // 2x2 matrix with all elements = 10
    auto c1 = Const(scope, 10, /* shape */ {2, 2});
    // 1x3x2x1 tensor
    auto c2 = Const(scope, {1, 2, 3, 4, 5, 6}, /* shape */ {1, 3, 2, 1});
    
    或通过以下任一方法直接将常量传递给其他操作构造函数
    // [1 1] * [41; 1]
    auto x = MatMul(scope, { {1, 1} }, { {41}, {1} });
    // [1 2 3 4] + 10
    auto y = Add(scope, {1, 2, 3, 4}, 10);
    

4. 图的执行

Scope root = Scope::NewRootScope();
auto c = Const(root, { {1, 1} });
auto m = MatMul(root, c, { {41}, {1} });

ClientSession session(root);
std::vector<Tensor> outputs;
session.Run({m}, &outputs);
// outputs[0] == {42}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值