Tensors

张量

正如名称所示,TensorFlow是定义和运行涉及张量的计算的框架。张量是向量和矩阵的一般化到潜在的更高的尺寸。在内部,TensorFlow将张量表示为基本数据类型的n维数组。

在编写一个TensorFlow程序时,你操作和传递的主要对象是tf.Tensor。一个tf.Tensor对象表示一个部分定义的计算,最终会产生一个值。TensorFlow程序首先建立一个tf.Tensor对象图,详细说明如何基于其他可用张量计算每个张量,然后运行该图的部分内容以获得期望的结果。

tf.Tensor具有以下属性:

  • a data type (float32, int32, or string, for example)

  • a shape

张量中的每个元素都具有相同的数据类型,并且数据类型总是已知的。形状(即它的尺寸数量和每个尺寸的大小)可能只是部分已知的。如果其输入的形状也是完全已知的,则大多数操作会产生完全已知形状的张量,但在某些情况下,只能在图形执行时找到张量的形状。

某些类型的张量是特殊的,这些将在程序员指南的其他单元中介绍。主要的是:

  • tf.Variable

  • tf.Constant

  • tf.Placeholder

  • tf.SparseTensor

除了tf.Variable张量的值是不变的,这意味着在单个执行张量的上下文中只有一个值。然而,两次评估相同的张量可能会返回不同的值; 例如张量可以是从磁盘读取数据或生成随机数的结果。

一的tf.Tensor对象是其尺寸的数量。等级的同义词包括顺序程度n维。请注意,TensorFlow中的排名与数学中的矩阵排名并不相同。如下表所示,TensorFlow中的每个等级都对应一个不同的数学实体:

RankMath entity
0Scalar (magnitude only)
1Vector (magnitude and direction)
2Matrix (table of numbers)
33-Tensor (cube of numbers)
nn-Tensor (you get the idea)

Rank 0

以下片段演示了如何创建几个0级变量:

mammal = tf.Variable("Elephant", tf.string) ignition = tf.Variable(451, tf.int16) floating = tf.Variable(3.14159265359, tf.float64) its_complicated = tf.Variable((12.3, -4.85), tf.complex64)

注意:字符串在TensorFlow中被视为单个项目,而不是字符序列。可以有标量字符串,字符串向量等。

秩1

要创建一个秩1的tf.Tensor对象,您可以传递一个项目列表作为初始值。例如:

mystr = tf.Variable(["Hello"], tf.string) cool_numbers = tf.Variable([3.14159, 2.71828], tf.float32) first_primes = tf.Variable([2, 3, 5, 7, 11], tf.int32) its_very_complicated = tf.Variable([(12.3, -4.85), (7.5, -6.23)], tf.complex64)

高阶秩

秩2 tf.Tensor对象由至少一行和至少一列组成:

mymat = tf.Variable([[7],[11]], tf.int16) myxor = tf.Variable([[False, True],[True, False]], tf.bool) linear_squares = tf.Variable([[4], [9], [16], [25]], tf.int32) squarish_squares = tf.Variable([ [4, 9], [16, 25] ], tf.int32) rank_of_squares = tf.rank(squarish_squares) mymatC = tf.Variable([[7],[11]], tf.int32)

更高级的张量同样由一个n维数组组成。例如,在图像处理过程中,会使用许多等级为4的张量,尺寸对应批量示例,图像宽度,图像高度和色彩通道。

my_image = tf.zeros([10, 299, 299, 3]) # batch x height x width x color

获取tf.Tensor对象的等级

要确定tf.Tensor对象的等级,请调用该tf.rank方法。例如,以下方法以编程方式确定tf.Tensor上一节中定义的等级:

r = tf.rank(my3d) # After the graph runs, r will hold the value 3.

参考tf.Tensor切片

由于tf.Tensor是单元格的n维数组,因此要访问单个单元格,tf.Tensor您需要指定n个索引。

对于0级张量(一个标量),没有指数是必要的,因为它已经是一个单一的数字。

对于秩1张量(矢量),传递单个索引允许您访问一个数字:

my_scalar = my_vector[2]

请注意,如果要从矢量中动态选择元素,则在 [] 内传递的索引[]本身可以是标量tf.Tensor

对于等级2或更高的张量,情况更加有趣。对于tf.Tensor等级2,通过两个数字返回标量,如预期的那样:

my_scalar = my_matrix[1, 2]

但是,传递一个数字将返回一个矩阵的子向量,如下所示:

my_row_vector = my_matrix[2] my_column_vector = my_matrix[:, 3]

:标记是作为“单独离开这个维度”Python切片语法。这在更高等级的张量中很有用,因为它允许你访问它的子向量,子矩阵,甚至其他副本。

形状

张量的形状是每个维度中元素的数量。TensorFlow在图形构建过程中自动推断形状。这些推断的形状可能具有已知或未知的等级。如果排名已知,则每个维度的大小可能是已知的或未知的。

TensorFlow文档使用三种符号约定来描述张量维度:等级,形状和维数。下表显示了它们如何相互关联:

形状维数
0[]0-d一个0-D张量。标量。
1D01-d一个形状为5的一维张量。
2D0,D12-d具有形状3,4的二维张量。
3D0,D1,D23-d一个形状为1,4,3的三维张量。
ñD0,D1,... Dn-1ND一个形状为D0,D1,... Dn-1的张量。

形状可以通过Python列表/元组的int或者tf.TensorShape显示。

获取tf.Tensor对象的形状

有两种方法可以访问tf.Tensor的形状。在构建图形时,询问已知的张量形状通常很有用。这可以通过读取对象的shape属性来完成tf.Tensor。此方法返回一个TensorShape对象,这是一种表示部分指定形状的方便方式(因为在构建图形时并不会完全知道所有形状)。

也可以在运行时得到一个tf.Tensor代表另一个完全定义形状的代码tf.Tensor。这是通过调用tf.shape操作完成的。这样,您可以构建一个图形,通过构建其他张量来控制张量的形状,这些张量取决于输入的动态形状tf.Tensor

例如,下面是如何制作与给定矩阵中的列数相同大小的零向量的方法:

zeros = tf.zeros(tf.shape(my_matrix)[1])

改变 tf.Tensor的形状

张量元素数量是其所有形状大小的乘积。标量的元素数量总是1。由于通常有许多不同的形状具有相同数量元素,因此能够改变tf.Tensor的形状并保持其元素固定通常是方便的。这可以用tf.reshape来完成。

以下示例演示如何重构张量:

rank_three_tensor = tf.ones([3, 4, 5]) matrix = tf.reshape(rank_three_tensor, [6, 10]) # Reshape existing content into # a 6x10 matrix matrixB = tf.reshape(matrix, [3, -1]) # Reshape existing content into a 3x20 # matrix. -1 tells reshape to calculate # the size of this dimension. matrixAlt = tf.reshape(matrixB, [4, 3, -1]) # Reshape existing content into a #4x3x5 tensor # Note that the number of elements of the reshaped Tensors has to match the # original number of elements. Therefore, the following example generates an # error because no possible value for the last dimension will match the number # of elements. yet_another = tf.reshape(matrixAlt, [13, 2, -1]) # ERROR!

数据类型

除维度外,张量具有数据类型。请参阅tf.DataType程序员指南中的页面以获取数据类型的完整列表。

不可能有一个tf.Tensor以上的数据类型。但是,可以将任意数据结构序列化为string并将其存储在tf.Tensor中。

可以使用以下方法将tf.Tensor从一个数据类型转换为另一个数据类型tf.cast

# Cast a constant integer tensor into floating point. float_tensor = tf.cast(tf.constant([1, 2, 3]), dtype=tf.float32)

要检查tf.Tensor数据类型,请使用该Tensor.dtype属性。

tf.Tensor从python对象创建时,您可以选择指定数据类型。如果你不这样做,TensorFlow会选择一个可以表示数据的数据类型。TensorFlow将Python整数转换为tf.int32Python浮点数tf.float32。否则,TensorFlow使用numpy在转换为数组时使用的相同规则。

评估 Tensors

一旦计算图建立完毕,您就可以运行生成特定tf.Tensor的计算并获取分配给它的值。这对于调试以及大部分TensorFlow工作都非常有用。

评估张量的最简单方法是使用Tensor.eval方法。例如:

constant = tf.constant([1, 2, 3]) tensor = constant * constant print tensor.eval()

eval方法仅在默认tf.Session值处于活动状态时才起作用(有关更多信息,请参阅图形和会话)。

Tensor.eval 返回一个与张量的内容相同的numpy数组。

有时不可能评估一个没有背景的tf.Tensor,因为它的值可能取决于不可用的动态信息。例如,依赖于Placeholder的张量不能在没有提供值的情况下进行评估Placeholder

p = tf.placeholder(tf.float32) t = p + 1.0 t.eval() # This will fail, since the placeholder did not get a value. t.eval(feed_dict={p:2.0}) # This will succeed because we're feeding a value # to the placeholder.

请注意,可以提供任何tf.Tensor,而不仅仅是占位符。

其他模型构造可能会使评估tf.Tensor变得复杂。TensorFlow无法直接评估tf.Tensor定义的函数内部或控制流结构内部。如果tf.Tensor取决于队列中的值,那么评估tf.Tensor只有在某些东西被排列后才会工作; 否则,评估它将被搁置。在处理队列时,请记住tf.train.start_queue_runners在评估任何tf.Tensors 之前先调用。

打印Tensor

出于调试目的,您可能想要打印tf.Tensor的值。虽然tfdbg提供了高级调试支持,但TensorFlow还可以直接打印tf.Tensor的值。

请注意,打a时很少使用以下模式tf.Tensor

t = <<some tensorflow operation>> print t # This will print the symbolic tensor when the graph is being built. # This tensor does not have a value in this context.

此代码打印tf.Tensor对象(代表延迟计算)而不是其值。相反,TensorFlow提供了这样的tf.Print操作,该操作返回其第一张张参数,同时打印tf.Tensor作为第二个参数传递的集合。

tf.Print必须正确使用它的返回值。看下面的例子

t = <<some tensorflow operation>> tf.Print(t, [t]) # This does nothing t = tf.Print(t, [t]) # Here we are using the value returned by tf.Print result = t + 1 # Now when result is evaluated the value of `t` will be printed.

当你评估result你会评估一切取决于result。由于result依赖t,并且评估t具有打印其输入(旧值t)的副作用,因此t被打印。