TensorFlow 核心数据结构:张量操作详解
张量基础概念
TensorFlow 中所有数据均以张量(Tensor)形式存在。张量本质上是多维数组的泛化,其维度数量称为阶(rank)或轴(axis)。
| 阶数 | 数学名称 | 示例 |
|---|---|---|
| 0 | 标量(Scalar) | 3.14 或 'hello' |
| 1 | 向量(Vector) | [10, 20, 30] |
| 2 | 矩阵(Matrix) | [[1, 2], [3, 4], [5, 6]] |
| 3+ | 高阶张量 | 图像数据 (batch, height, width, channels) |
实际工程实践中,处理对象多为低阶张量(0-2阶)。张量在计算图中作为节点存在,分为常量(tf.constant)与变量(tf.Variable)两类:前者值固定不变,后者支持运行时更新。
常量与变量的创建
以下示例展示 TensorFlow 1.x 中张量的基本定义与会话执行:
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# 定义常量
alpha = tf.constant([7.2], name="alpha_const")
# 定义变量并重新赋值
beta = tf.Variable([0], name="beta_var")
beta = beta.assign([9])
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print("alpha:", sess.run(alpha))
print("beta: ", sess.run(beta))
输出结果:
alpha: [7.2]
beta: [9]
计算图中的加法运算
显式创建计算图有助于复杂模型中的状态管理:
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
graph = tf.Graph()
with graph.as_default():
m = tf.constant(12, name="m_val")
n = tf.constant(7, name="n_val")
p = tf.constant(3, name="p_val")
partial = tf.add(m, n, name="m_plus_n")
total = tf.add(partial, p, name="complete_sum")
with tf.Session() as sess:
print("partial:", partial.eval())
print("total: ", total.eval())
输出结果:
partial: 19
total: 22
Eager 模式下的向量运算与广播
启用 Eager Execution 后,TensorFlow 支持即时计算,无需显式会话:
import tensorflow as tf
# 启用 Eager Execution(TF 2.x 默认开启)
try:
tf.contrib.eager.enable_eager_execution()
print("Eager execution enabled!")
except ValueError:
pass
# 向量创建与元素级运算
fibonacci = tf.constant([1, 1, 2, 3, 5, 8], dtype=tf.int32)
unit = tf.ones([6], dtype=tf.int32)
next_fib = tf.add(fibonacci, unit)
double_fib = fibonacci * tf.constant(2, dtype=tf.int32) # 标量广播
print("fibonacci:", fibonacci.numpy())
print("next_fib: ", next_fib.numpy())
print("double: ", double_fib.numpy())
# 矩阵及其属性
sample = tf.constant([[10, 20, 30], [40, 50, 60]], dtype=tf.int32)
print("\nMatrix shape:", sample.shape)
print("Matrix value:\n", sample.numpy())
输出结果:
fibonacci: [1 1 2 3 5 8]
next_fib: [2 2 3 4 6 9]
double: [ 2 2 4 6 10 16]
Matrix shape: (2, 3)
Matrix value:
[[10 20 30]
[40 50 60]]
形状操作与维度变换
通过 tf.reshape 可在保持元素总数不变的前提下调整张量结构:
import tensorflow as tf
tf.compat.v1.enable_eager_execution()
# 原始 4x2 矩阵
original = tf.constant([[1, 2], [3, 4], [5, 6], [7, 8]], dtype=tf.int32)
# 多种变形方式
flat = tf.reshape(original, [8]) # 展平为一维
wide = tf.reshape(original, [2, 4]) # 变为 2x4
deep = tf.reshape(original, [2, 2, 2]) # 三维张量
print("Original (4x2):\n", original.numpy())
print("\nFlattened (8):\n", flat.numpy())
print("\nWide (2x4):\n", wide.numpy())
print("\nDeep (2x2x2):\n", deep.numpy())
输出结果:
Original (4x2):
[[1 2]
[3 4]
[5 6]
[7 8]]
Flattened (8):
[1 2 3 4 5 6 7 8]
Wide (2x4):
[[1 2 3 4]
[5 6 7 8]]
Deep (2x2x2):
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
矩阵乘法与随机初始化
矩阵乘法遵循线性代数规则,前矩阵列数须等于后矩阵行数:
import tensorflow as tf
tf.compat.v1.enable_eager_execution()
# 矩阵乘法: (3x4) @ (4x2) = (3x2)
left = tf.constant([[2, 3, 1, 0], [1, -1, 2, 4], [0, 2, -1, 3]], dtype=tf.int32)
right = tf.constant([[1, 2], [3, 4], [5, 6], [7, 8]], dtype=tf.int32)
product = tf.matmul(left, right)
print("Product (3x2):\n", product.numpy())
# 变量初始化与正态分布
gamma = tf.Variable([5], dtype=tf.float32)
delta = tf.Variable(tf.random.normal(shape=[1, 3], mean=0.0, stddev=1.0, seed=42))
# 赋值操作
gamma.assign([10])
print("\ngamma:", gamma.numpy())
print("delta:", delta.numpy())
输出结果:
Product (3x2):
[[16 24]
[37 46]
[20 26]]
gamma: [10.]
delta: [[ 0.32746854 -0.84243774 0.31939507]]
关键要点总结
- 广播机制:较小维度张量自动扩展以匹配较大维度,避免显式复制数据
- 形状兼容性:
tf.assign要求目标与源形状严格一致 - 变形约束:
tf.reshape前后元素总数必须相等 - 随机种子:固定
seed参数确保实验可复现