"""Run independent Core, Lite and reusable SavedModel exercises."""
import json
import platform
from pathlib import Path
from tempfile import TemporaryDirectory
import numpy as np
import tensorflow as tf
def record(cases, name, inputs, prerequisites, action, expected, actual):
assert actual == expected, (name, actual, expected)
cases.append(dict(name=name, inputs=inputs, prerequisites=prerequisites, action=action,
expected=expected, actual=actual, passed=True))
class LocalEmbedding(tf.Module):
@tf.function(input_signature=[tf.TensorSpec([None], tf.string)])
def __call__(self, batch):
match = tf.cast(tf.equal(batch, "cloud"), tf.float32)
return tf.stack((match, 1 - match), axis=-1)
def verify(cases):
table = tf.constant([[3, 5], [7, 11]])
value = tf.Variable(3.0)
with tf.GradientTape() as tape:
squared = value ** 2
actual = [table.numpy().tolist(), table.dtype.name, float(tape.gradient(squared, value))]
record(cases, "core_tensor", {"matrix": [[3, 5], [7, 11]], "gradient_at": 3},
"TensorFlow eager execution and trainable scalar", "Read the tensor and differentiate x²",
[[[3, 5], [7, 11]], "int32", 6.0], actual)
with TemporaryDirectory(prefix="tensorflow-ecosystem-") as temp:
base = Path(temp)
tf.keras.utils.set_random_seed(31)
model = tf.keras.Sequential([
tf.keras.Input((4, 4, 1)),
tf.keras.layers.Conv2D(3, (2, 2), activation="relu"),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(2),
])
model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.01),
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True))
images = np.asarray([np.eye(4), np.fliplr(np.eye(4)), np.ones((4, 4)), np.zeros((4, 4))],
dtype=np.float32)[..., None]
loss = float(model.train_on_batch(images, np.asarray([0, 1, 0, 1])))
saved = base / "tiny-cnn"
model.export(saved, verbose=False)
lite = tf.lite.TFLiteConverter.from_saved_model(str(saved)).convert()
interpreter = tf.lite.Interpreter(model_content=lite)
interpreter.allocate_tensors()
sample = images[:1]
inputs, = interpreter.get_input_details()
outputs, = interpreter.get_output_details()
interpreter.set_tensor(inputs["index"], sample)
interpreter.invoke()
result = interpreter.get_tensor(outputs["index"])
reference = model(sample, training=False).numpy()
np.testing.assert_allclose(result, reference, rtol=1e-5, atol=1e-6)
record(cases, "lite_cnn_cpu", {"training_images": 4, "input_shape": list(sample.shape)},
"Tiny seeded CNN, Lite CPU Interpreter after allocating tensors",
"Train one batch, export, convert and compare both class scores",
[True, [1, 2], True, True],
[bool(np.isfinite(loss)), list(result.shape), len(lite) > 0,
int(np.argmax(result)) == int(np.argmax(reference))])
cases[-1]["measurements"] = {"bn": len(lite), "max_abs_error": float(np.max(abs(result - reference))),
"loss": loss, "scores": result.tolist()}
model_path = base / "embedding"
tf.saved_model.save(LocalEmbedding(), model_path)
embed = tf.saved_model.load(model_path)
tokens = ["cloud", "river"]
values = embed(tf.constant(tokens)).numpy().tolist()
record(cases, "local_embedding_contract", tokens,
"Site-owned exported callable SavedModel", "Reload the model and predict two strings",
[[1.0, 0.0], [0.0, 1.0]], values)
if __name__ == "__main__":
observations = []
verify(observations)
print(json.dumps(dict(version=platform.python_version(), tensorflow=tf.__version__,
keras=tf.keras.__version__, system=platform.system(),
devices=[device.name for device in tf.config.list_physical_devices()],
cases=observations), ensure_ascii=True))
本例需在 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-ecosystem-lab/verify-tensorflow-ecosystem.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
verify-tensorflow-ecosystem.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a359.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a365.zip