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}