TensorFlow 核心概念
逐项运行张量属性、兼容会话、函数图、变量、自动微分与小型训练。
学完这一章,你能够
- 逐项运行张量属性、兼容会话、函数图、变量、自动微分与小型训练。
用秩、形状、类型与设备描述张量
从运算接口看,张量可有零个或多个轴。标量秩为 0,向量秩为 1,矩阵秩为 2。形状 (2,3) 表示两行三列;秩与矩阵的线性代数秩不同。数值例分别取 float32、int32,另有 bool 和 string。用张量的 device 字段与设备枚举确认 CPU 或 GPU。当前实验观察到 CPU。
输入、权重、偏置、中间激活与损失都可以用张量表示。带批量的 RGB 图片常用 [批,高,宽,通道];分词 ID 常用 [批,序列长度];时序特征常用 [批,时间步,特征]。输入形状要和模型实际约定对应。
按依赖顺序运行算子
在 z=(x+y)w 中,输入 x=2、y=4、w=3,先加得 6,再乘得 18。追踪图中能定位加法与乘法节点。图也可以记录值的依赖与控制关系。

追踪图可以用于自动微分、优化器重排、向量化、设备分配或可视化。是否获得提速要用相同负载记录预热和执行;分布式环境需额外配置。用 TensorBoard 可以看已记录的图和指标。
区分会话、即时执行和函数追踪
兼容分支在独立 Graph 中定义形状 [None,784] 的占位符、权重和偏置,进入 Session 后初始化变量,再由 feed_dict 传入一个 784 列的样本。现代分支直接处理即时张量。兼容图不需要在当前进程全局关闭即时执行。
即时计算支持立刻读取 NumPy 值。tf.function 按输入签名追踪成 ConcreteFunction;追踪成本、运算量和形状变化都影响速度。固定签名、关闭 Python 副作用,再比较真实速度。
比较固定张量和可更新变量
tf.constant 创建不可原位赋值的张量。变量可用 assign 替换值或通过切片 assign 修改局部,可被优化器更新并保存在检查点中。GradientTape 默认自动观察参与运算的可训练变量,需对普通浮点 Tensor 明确调用 watch。内存寿命取决于引用、图和缓冲分配策略。
把前向、梯度和参数更新串起来
先用两层固定权重得到确定的预测,再用 GradientTape 记录运算。对 x=3 的函数 x²+2x+1 得到导数 8。训练例用 keras Dense 与 Adam,将逐样本损失归约成标量,再应用参数梯度。旧例直接格式化向量损失会失败;示例同时检查损失形状和收敛结果。
完整链路从输入张量流向运算和预测,损失经链式法则得到梯度,再写回变量。末图用本章实际前向、梯度及训练结果给出可对照的流程。

变量与固定张量的区别
| 比较项 | 变量 | 固定张量 |
|---|---|---|
| 更新接口 | 可通过 assign 改值。 | 值不可原地赋值。 |
| 常见职责 | 模型权重与优化状态。 | 输入、固定系数和超参数。 |
| 何时被跟踪 | 可训练变量通常自动被观察。 | 浮点张量可显式 watch。 |
| 状态寿命 | 由持有者管理,可能跨步保留。 | 依引用和运行时生命周期保留,不能一概称临时。 |
| 写法 | tf.Variable 可指定初值。 | tf.constant 可指定 dtype。 |
执行量化的张量、函数图和训练接口
"""Verify tensors, graphs, variables and scalar-loss training on the CPU."""
from pathlib import Path
from tempfile import TemporaryDirectory
import json
import platform
import tensorflow as tf
def observe(cases, name, operation, inputs, expected, actual):
assert actual == expected, (name, expected, actual)
cases.append(dict(name=name, operation=operation, inputs=inputs, expected=expected, actual=actual, passed=True))
def finish(cases):
print(json.dumps(dict(version=platform.python_version(),tensorflow=tf.__version__,
keras=tf.keras.__version__,system=platform.system(),
devices=[d.name for d in tf.config.list_physical_devices()],
cases=cases), ensure_ascii=False))
def main():
cases=[]
parts=[tf.constant(5),tf.constant([1,2,3,4]),tf.constant([[1,2],[3,4]])]
observe(cases,"tensor_rank_examples","compare scalar, vector and matrix ranks",
[5,[1,2,3,4],[[1,2],[3,4]]],[0,1,2],[int(tf.rank(t)) for t in parts])
matrix=tf.constant([[1,2,3],[4,5,6]])
dtypes=[tf.constant(1.).dtype.name,matrix.dtype.name,tf.constant(True).dtype.name,tf.constant("text").dtype.name]
observe(cases,"tensor_metadata","read shape, dtype, rank and CPU placement",
matrix.numpy().tolist(),[[2,3],["float32","int32","bool","string"],2,True],
[list(matrix.shape),dtypes,int(tf.rank(matrix)),matrix.device.endswith("CPU:0")])
shapes=[tf.zeros((2,224,224,3)),tf.zeros((2,7),tf.int32),tf.zeros((2,4,3))]
observe(cases,"input_layouts","construct image, token and time-series inputs",
{"batch":2},[[2,224,224,3],[2,7],[2,4,3]],[list(x.shape) for x in shapes])
@tf.function
def data_flow(a,b,c):
return tf.multiply(tf.add(a,b),c)
arguments=tuple(tf.constant(v) for v in (2,4,3))
f=data_flow.get_concrete_function(*arguments)
types={op.type for op in f.graph.get_operations()}
observe(cases,"add_then_multiply_trace","execute an add/multiply trace and inspect graph nodes",
[2,4,3],[18,True],[int(f(*arguments)),{"AddV2","Mul"}<=types])
graph=tf.Graph()
with graph.as_default():
x=tf.compat.v1.placeholder(tf.float32,shape=[None,784])
w=tf.Variable(tf.ones((784,10)))
b=tf.Variable(tf.ones(10))
out=x@w+b
init=tf.compat.v1.global_variables_initializer()
conf=tf.compat.v1.ConfigProto(intra_op_parallelism_threads=1,inter_op_parallelism_threads=1)
with tf.compat.v1.Session(graph=graph,config=conf) as session:
session.run(init)
value=session.run(out,{x:[[1.]*784]})
observe(cases,"legacy_session_feed","initialize explicit graph state and feed one 784-element input",
{"feed_shape":[1,784],"output_features":10},[[1,10],785.],
[list(value.shape),float(value[0,0])])
eager=tf.constant([[1.,2.,3.]])@tf.Variable([[1.,0.],[0.,2.],[1.,1.]])+tf.constant([1.,0.])
observe(cases,"eager_matmul","multiply an eager row by fixed weights and add bias",
[1,2,3],[[5.,7.]],eager.numpy().tolist())
eager_sum=tf.constant(2.)+tf.constant(3.)
observe(cases,"eager_read","read the immediate sum", [2,3],[True,5.],[tf.executing_eagerly(),float(eager_sum.numpy())])
@tf.function
def expression(a,b):
return a*b+a
trace=expression.get_concrete_function(tf.constant(2.),tf.constant(3.))
observe(cases,"traced_function","construct and run a concrete function", [2,3],8.,float(trace(tf.constant(2.),tf.constant(3.)).numpy()))
fixed=[tf.constant(.01),tf.constant([1.,2.,3.,4.]),tf.constant([[1.,2.],[3.,4.]])]
observe(cases,"constant_shapes","create fixed tensors with several ranks and check absence of in-place assign",
{"learning_rate":.01},[[[],[4],[2,2]],True],
[[list(c.shape) for c in fixed], all(not hasattr(c,"assign") for c in fixed)])
mutable=tf.Variable(tf.zeros((2,3)))
mutable.assign(tf.ones((2,3)))
mutable[0,0].assign(5.)
observe(cases,"variable_assign_and_slice","replace all values and update one element",
{"shape":[2,3],"top_left":5},[[5.,1.,1.],[1.,1.,1.]],mutable.numpy().tolist())
with TemporaryDirectory(prefix="tf-variable-") as local:
checkpoint=tf.train.Checkpoint(target=mutable)
saved=checkpoint.write(str(Path(local)/"tensor-variables"))
mutable.assign(tf.zeros((2,3)))
checkpoint.read(saved).assert_consumed()
observe(cases,"checkpoint_restores_variable","save state then restore after zeroing",
{"top_left":5},5.,float(mutable[0,0].numpy()))
first=tf.constant([[1.,2.]])
h=tf.nn.relu(first@tf.constant([[1.,-2.,1.],[2.,0.,-1.]])+tf.constant([0.,0.,0.]))
y=h@tf.constant([[2.],[1.],[3.]])+tf.constant([1.])
observe(cases,"two_layer_forward","apply an affine ReLU layer and a scalar readout",
first.numpy().tolist(),[[[5.,0.,0.]],[[11.]]],[h.numpy().tolist(),y.numpy().tolist()])
inp=tf.Variable(3.)
with tf.GradientTape() as tape:
objective=inp**2+2*inp+1
observe(cases,"derivative_at_three","differentiate a quadratic in an automatically watched variable",
3,8.,float(tape.gradient(objective,inp)))
input_const=tf.constant(3.)
with tf.GradientTape() as tape:
tape.watch(input_const)
fixed_loss=input_const**2
observe(cases,"watched_tensor_has_gradient","explicitly watch a fixed floating point tensor",
3,6.,float(tape.gradient(fixed_loss,input_const)))
model=tf.keras.Sequential([tf.keras.Input(shape=(1,)),tf.keras.layers.Dense(1,kernel_initializer="zeros",bias_initializer="zeros")])
opt=tf.keras.optimizers.Adam(.1)
train=tf.constant([[-1.],[0.],[1.]])
target=tf.constant([[-1.],[1.],[3.]])
per_example=tf.keras.losses.MeanSquaredError(reduction="none")
vector=per_example(target,model(train))
rejected=False
try:
format(vector,".4f")
except (TypeError,ValueError):
rejected=True
observe(cases,"vector_losses_need_reduction","compare per-example shape and the formatted scalar path",
{"batch_count":3},[[3],True],[list(vector.shape),rejected])
@tf.function
def train_scalar(x,y):
with tf.GradientTape() as tape:
value=tf.reduce_mean(per_example(y,model(x)))
grads=tape.gradient(value,model.trainable_variables)
opt.apply_gradients(zip(grads,model.trainable_variables))
return value
initial=float(tf.reduce_mean(vector))
for _ in range(80):
training=train_scalar(train,target)
final=float(tf.reduce_mean(per_example(target,model(train))))
observe(cases,"scalar_adam_training","minimize a scalar over 80 updates and check resulting loss",
{"steps":80,"rate":.1},[[],True,True],[list(training.shape),abs(initial-11/3)<1e-6,final<.002])
finish(cases)
if __name__=="__main__":
main()
- 斜率导数为 8。两层前向输出、旧会话输入和标量训练误差各有固定观察。
所需环境:Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。
当前源码 SHA256:55f43fa522fc8afc5fd507dd2e01693dc0285bd0c904b98027ab2022a181d0ea
本地运行
解压后按 README 运行本站程序。
所需环境:Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。
ZIP SHA256:f4a3ee2b7ff5bd47230fb9c120b66fd00f47c7292393fb91489acee553f516ad
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
普通浮点张量什么时候能作为求导源?
展开参考解答
在记录区域内对它显式 watch,并确保它与目标值有可微连接。