"""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()
本例需在 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。
入口文件:projects/tensorflow-core-concepts-lab/tensor-graph-and-gradient.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
tensor-graph-and-gradient.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a361.zip
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a359.zip