对于tensorflow框架的了解可参见: TensorFlow: Large-Scale Machine Learning on Heterogeneous Distributed Systems这篇google的whitepaper2015。
tensorflow中的一些对象的含义
图( GraphDef 和 Graph )
GraphDef 即:序列化的图定义对象。
可使用ConvertGraphDefToGraph函数将GraphDef构建成Graph
Graph 是节点node的组织关系,包含节点的关联关系(edge)和节点对数据的操作计算(opeartion即op)
节点(NodeDef 和 Node):
包含:节点名(Node name),操作名(operation name),输入(input),执行设备(device),属性(attr).
在一个图中,节点名唯一;
不同的节点名可以有同样的操作名;
操作(op):
操作(operation)拥有一个命名,代表一个抽象运算(例如:矩阵相乘运算或加运算)
包含:操作名(operation name),输入参数(input ArgDef),输出参数(output ArgDef),属性(attr),操作描述(doc string),优化设置等。
通过调用REGISTER_OP来注册操作(operation)
例如:定义一个绝对值运算操作
REGISTER_OP("Abs") /*“Abs”为操作名*/
.Input("x: T") /*输入参数 x 类型为T*/
.Output("y: T")/*输出参数 y 类型为T*/
.Attr("T: {half, float, double, int32, int64}")/*T的类型可以为大括号中的任一种*/
.SetShapeFn(shape_inference::UnchangedShape)/*输入与输出的结构(维度、数据长度)是否变化*/
.Doc(R"doc(
Computes the absolute value of a tensor.
Given a tensor `x`, this operation returns a tensor containing the absolute
value of each element in `x`. For example, if x is an input element and y is
an output element, this operation computes \\(y = |x|\\).
)doc");/*操作符描述*/
通过OP我们可以注册一种操作(数据流操作或控制流操作);
对于数据流操作用数学观点描述实质就是函数。大家都学过函数f,对于给定输入x(x可以为标量、向量、矩阵、多维矩阵等),其对应的输出y(x可以为标量、向量、矩阵、多维矩阵等)
即
定义op的梯度
例如:定义绝对值运算操作的梯度
Status AbsGrad(const AttrSlice& attrs, FunctionDef* g) {
return GradForUnaryCwise(g, {
{{"sign"}, "Sign", {"x"}, {}, {"dy"}},/*sign 节点*/
{{"dx"}, "Mul", {"dy", "sign"}},/*Mul 节点*/
});
}
REGISTER_OP_GRADIENT("Abs", AbsGrad);
sign 操作
Mul 操作
张量(Tensor)
tensor 代表N维数组
TensorShape 代表张量的特征(维度、各维元素长度、元素类型)
操作核(KernelDef 和 OpKernel):
OpKernel 表示 操作(operation)的特定实现,运行在某一个特定类型的设备(如:CPU或GPU)。
包含:操作名(operation name),核运行的设备(device)等。
TensorFlow二进制通过注册机制定义内核组。
例如注册Abs核
REGISTER_KERNEL_BUILDER(Name("Abs")
.Device(DEVICE_GPU)
.HostMemory("x")
.HostMemory("y")
.TypeConstraint<int32>("T"),
UnaryOp<CPUDevice, functor::abs<int32>>);