张量(Tensor)是 TensorFlow 的核心数据结构,可以理解为多维数组。无论是机器学习模型还是深度学习算法,张量都是数据流动的基础载体。🧠

📌 什么是张量?

在 TensorFlow 中,张量是数据的多维数组,具有以下特性:

  • 维度(Rank):张量的轴数,例如标量是 0 维,向量是 1 维,矩阵是 2 维
  • 形状(Shape):各维度的大小,如 (3, 4) 表示 3 行 4 列的矩阵
  • 数据类型(Type):支持 float32int32bool 等多种类型
TensorFlow_张量

🧮 张量的创建与操作

import tensorflow as tf

# 创建标量(0维张量)
scalar = tf.constant(5)
print(scalar)  # 输出: tf.Tensor(5, shape=(), dtype=int32)

# 创建向量(1维张量)
vector = tf.constant([1, 2, 3], shape=[3])
print(vector)  # 输出: tf.Tensor([1 2 3], shape=(3,), dtype=int32)

# 创建矩阵(2维张量)
matrix = tf.constant([[1, 2], [3, 4]])
print(matrix)  # 输出: tf.Tensor([[1 2]
                                 #  [3 4]], shape=(2, 2), dtype=int32)

🔄 张量的广播机制

TensorFlow 支持自动广播(Broadcasting)操作,例如:

# 向量与标量相加
result = tf.add(vector, scalar)
print(result)  # 输出: tf.Tensor([6 7 8], shape=(3,), dtype=int32)

📚 扩展阅读

想深入了解张量的进阶操作?可以查看我们的张量与操作教程。📖

张量_应用