【TensorFlow】笔记:基础知识-张量操作(二)
TensorFlow 使用 张量 (Tensor)作为数据的基本单位。张量的重要属性是其形状、类型和值。可以通过张量的 shape 、 dtype 属性和 numpy() 方法获得。
01
形状简介
张量有形状。下面是几个相关术语:
形状:张量的每个维度的长度(元素数量)。
秩:张量的维度数量。标量的秩为 0,向量的秩为 1,矩阵的秩为 2。
轴或维度:张量的一个特殊维度。
大小:张量的总项数,即乘积形状向量
tensor = tf.zeros([3, 2, 4, 5])
print("Type of every element:", tensor.dtype)print("Number of dimensions:", tensor.ndim)print("Shape of tensor:",tensor.shape)print("Elements along axis 0 of tensor:", tensor.shape[0])print("Elements along the last axis of tensor:", tensor.shape[-1])print("Total number of elements (3*2*4*5): ", tf.size(tensor).numpy())# outputType of every element:Number of dimensions: 4Shape of tensor: (3, 2, 4, 5)Elements along axis 0 of tensor: 3Elements along the last axis of tensor: 5Total number of elements (3*2*4*5): 120
虽然通常用索引来指代轴,但是您始终要记住每个轴的含义。轴一般按照从全局到局部的顺序进行排序:首先是批次轴,随后是空间维度,最后是每个位置的特征。这样,在内存中,特征向量就会位于连续的区域。

02
索引
单轴索引
TensorFlow 遵循标准 Python 索引规则(类似于在 Python 中为列表或字符串编制索引)以及 NumPy 索引的基本规则。
索引从
0开始编制负索引表示按倒序编制索引
冒号
:用于切片start:stop:step
tensor1 = tf.constant([0, 1, 1, 2, 3, 5, 8, 13, 21, 34])print(tensor1.numpy())# output[ 0 1 1 2 3 5 8 13 21 34
使用标量编制索引会移除维度:
print("First:", tensor1[0].numpy())print("Second:", tensor1[1].numpy())print("Last:", tensor1[-1].numpy())# outputFirst: 0Second: 1Last: 34
使用 : 切片编制索引会保留维度:
print("Everything:", tensor1[:].numpy())print("Before 4:", tensor1[:4].numpy())print("From 4 to the end:", tensor1[4:].numpy())print("From 2, before 7:", tensor1[2:7].numpy())print("Every other item:", tensor1[::2].numpy())print("Reversed:", tensor1[::-1].numpy())# outputEverything: [ 0 1 1 2 3 5 8 13 21 34]Before 4: [0 1 1 2]From 4 to the end: [ 3 5 8 13 21 34]From 2, before 7: [1 2 3 5 8]Every other item: [ 0 1 3 8 21]Reversed: [34 21 13 8 5 3 2 1 1 0]
多轴索引:
更高秩的张量通过传递多个索引来编制索引。
对于高秩张量的每个单独的轴,遵循与单轴情形完全相同的索引规则。
tensor2 = tf.constant([[1, 2],[3, 4],[5, 6]], dtype=tf.float16)print(tensor2.numpy())# output[[1. 2.][3. 4.][5. 6.]]
为每个索引传递一个整数,结果是一个标量。
print(tensor2[1, 1].numpy())# output4.0
还可以使用整数与切片的任意组合编制索引:
# Get row and column tensorsprint("Second row:", tensor2[1, :].numpy())print("Second column:", tensor2[:, 1].numpy())print("Last row:", tensor2[-1, :].numpy())print("First item in last column:", tensor2[0, -1].numpy())print("Skip the first row:")print(tensor2[1:, :].numpy(), "\n")# outputSecond row: [3. 4.]Second column: [2. 4. 6.]Last row: [5. 6.]First item in last column: 2.0Skip the first row:[[3. 4.][5. 6.]]
下面是一个 3 轴张量的示例:
tensor3 = tf.constant([[],[]],[],[]],[],[]],])print(tensor3)tf.Tensor([][]][][]][][]]], shape=(3, 2, 5), dtype=int32)

选择批次中每个示例的所有位置的最后一个特征:
print(tensor3[:, :, 4]# outputtf.Tensor([[ 4 9][14 19][24 29]], shape=(3, 2), dtype=int32)

参考文献:文档主要参考TensorFlow官网
点击上方“蓝字”关注本公众号
点击上方“蓝字”关注本公众号
END
扫码关注
微信号|sdxx_rmbj
评论
