机器学习与深度学习 / 系统课时
创建与查看张量
创建与查看张量
张量是 TensorFlow 中承载数据的基本对象。本课直接创建标量、向量和矩阵,并读取 shape、ndim、dtype、元素数量等属性。完成后,你可以在模型输入、损失计算或数据预处理前快速确认张量结构是否符合预期。
学习目标
- 使用
tf.constant创建不同维度的常量张量。 - 正确区分形状、维度数量、元素数量和数据类型。
- 通过可运行代码检查张量的实际值与结构。
用 tf.constant 创建张量
tf.constant 会根据传入的数据创建不可变张量。单个数字得到 0 维标量,一维列表得到向量,嵌套列表则可以得到矩阵或更高维张量。实际项目中建议在数据类型有明确要求时显式填写 dtype,避免后续算子出现类型不一致。
下面的示例适用于 TensorFlow 2.x,并可直接运行。
import tensorflow as tf
scalar = tf.constant(7)
vector = tf.constant([10, 20, 30], dtype=tf.int32)
matrix = tf.constant([
[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
], dtype=tf.float32)
print(scalar)
print(vector)
print(matrix)预期输出
tf.Tensor(7, shape=(), dtype=int32)
tf.Tensor([10 20 30], shape=(3,), dtype=int32)
tf.Tensor(
[[1. 2. 3.]
[4. 5. 6.]], shape=(2, 3), dtype=float32)这里 shape=() 表示标量没有轴;shape=(3,) 表示只有一个长度为 3 的轴;shape=(2, 3) 表示矩阵有 2 行、3 列。创建嵌套张量时,每一行长度必须兼容,否则不能直接构成普通稠密张量。
读取形状和维度
tensor.shape 返回静态形状信息,tensor.ndim 返回轴的数量。对于形状为 (2, 3) 的矩阵,维度数量是 2,而不是 6;6 是元素总数。动态计算图中也可以使用 tf.shape 和 tf.rank 获取运行时结果。
import tensorflow as tf
x = tf.constant([
[1, 2, 3],
[4, 5, 6],
], dtype=tf.int32)
print("shape:", x.shape)
print("ndim:", x.ndim)
print("runtime shape:", tf.shape(x).numpy())
print("rank:", tf.rank(x).numpy())预期输出
shape: (2, 3)
ndim: 2
runtime shape: [2 3]
rank: 2TensorFlow 2.x 默认启用 eager execution,因此示例中的 .numpy() 可以直接把结果取回为 NumPy 值。在 tf.function 构建的图内部,不应依赖 .numpy() 获取中间结果,而应继续使用 TensorFlow 算子处理。
检查数据类型和元素数量
dtype 决定张量元素采用什么数值表示,tf.size 则返回全部元素的数量。对于模型输入,常见浮点类型是 tf.float32;类别索引、计数等数据常使用 tf.int32 或 tf.int64。不要通过肉眼观察数值猜测类型,应直接读取属性。
import tensorflow as tf
scores = tf.constant([
[0.2, 0.8],
[0.6, 0.4],
], dtype=tf.float32)
print("dtype:", scores.dtype)
print("elements:", tf.size(scores).numpy())
print("first row:", scores[0].numpy())预期输出
dtype: <dtype: 'float32'>
elements: 4
first row: [0.2 0.8]形状 (2, 2)、维度数量 2 和元素数量 4 描述的是三个不同概念。排查模型输入问题时,至少同时确认 shape 与 dtype,因为形状正确但数据类型错误,同样可能让后续算子无法执行。
避免把张量结构看错
最常见的错误是把 (3,) 与 (3, 1) 当成同一种形状。前者是一维向量,后者是二维列矩阵,在广播、矩阵乘法以及神经网络输入中可能产生完全不同的结果。可以直接打印两者的形状进行确认。
import tensorflow as tf
a = tf.constant([1, 2, 3])
b = tf.constant([[1], [2], [3]])
print(a.shape, a.ndim)
print(b.shape, b.ndim)预期输出
(3,) 1
(3, 1) 2当输入模型前不确定数据结构时,优先检查 tensor.shape、tensor.ndim 和 tensor.dtype。这三个信息通常足以快速发现少了一维、多了一维或整数误传给浮点计算等基础问题。