"""Run the TensorFlow CPU example with fixed inputs and one explicit training update."""
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=[]
with tf.device("/CPU:0"):
x=tf.constant([[-1.],[1.]])
target=tf.constant([[-1.],[3.]])
w=tf.Variable([[0.]])
b=tf.Variable([0.])
use=lambda data: data@w+b
observe(cases,"tensor_shape_and_device","construct a CPU tensor and inspect its metadata",
[[-1.],[1.]], [[2,1],"float32",True],[list(x.shape),x.dtype.name,x.device.endswith("CPU:0")])
observe(cases,"eager_tensor_result","multiply a fixed input and read the numeric result",
{"x":[-1,1],"slope":2},[[1.],[5.]],(2*x+3).numpy().tolist())
with tf.GradientTape() as tape:
start=tf.reduce_mean(tf.square(use(x)-target))
changes=tape.gradient(start,[w,b])
observe(cases,"two_parameter_gradients","differentiate the mean square error",
{"target":[-1,3]},[5.,[[-4.]],[ -2.]],
[float(start.numpy()),changes[0].numpy().tolist(),changes[1].numpy().tolist()])
tf.keras.optimizers.SGD(.25).apply_gradients(zip(changes,[w,b]))
after=tf.reduce_mean(tf.square(use(x)-target))
observe(cases,"one_real_update","apply one SGD step and recompute the objective",
{"learning_rate":.25},[[[1.]],[.5],1.25],[w.numpy().tolist(),b.numpy().tolist(),float(after.numpy())])
data=tf.data.Dataset.from_tensor_slices((x,target)).batch(2)
opts=tf.data.Options()
opts.threading.private_threadpool_size=1
batch_x,batch_y=next(iter(data.with_options(opts)))
observe(cases,"labeled_batch_shape","read a batch of features and the corresponding labels",
{"batch_size":2},[[[-1.],[1.]],[[-1.],[3.]]],[batch_x.numpy().tolist(),batch_y.numpy().tolist()])
layer=tf.keras.layers.Dense(1,kernel_initializer="ones",bias_initializer=tf.keras.initializers.Constant(.5))
observe(cases,"equivalent_keras_layer","run a matching affine layer on a second input batch",
[[2.],[4.]],[[2.5],[4.5]],layer(tf.constant([[2.],[4.]])).numpy().tolist())
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-overview-lab/first-tensorflow-step.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
first-tensorflow-step.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a359.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a375.zip