蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

比较即时图、兼容会话与保存后加载

PYTHONWindows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。compare-execution-modes.py
compare-execution-modes.py74 行
"""Compare several TensorFlow execution styles on the same fixed calculation."""
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=[]
    x=tf.constant([2.,4.],dtype=tf.float32)
    eager=3*x+1
    observe(cases,"eager_vector","multiply and add without a session",
            x.numpy().tolist(), [7.,13.],eager.numpy().tolist())

    @tf.function(input_signature=[tf.TensorSpec([None],tf.float32)])
    def compiled(value):
        return 3*value+1

    traced=compiled(x)
    observe(cases,"eager_and_function_match","execute the traced graph and record its operation types",
            [2.,4.],[[7.,13.],True],
            [traced.numpy().tolist(),{"Mul","AddV2"}.issubset({op.type for op in compiled.get_concrete_function().graph.get_operations()})])
    second=compiled(tf.constant([1.,0.,-1.]))
    observe(cases,"fixed_signature_handles_multiple_lengths","run a new vector length with the same shape signature",
            [1.,0.,-1.],[[4.,1.,-2.],1],[second.numpy().tolist(),compiled.experimental_get_tracing_count()])

    graph=tf.Graph()
    with graph.as_default():
        old_x=tf.compat.v1.placeholder(tf.float32,shape=[None])
        old_y=3*old_x+1
    config=tf.compat.v1.ConfigProto(intra_op_parallelism_threads=1,inter_op_parallelism_threads=1)
    with tf.compat.v1.Session(graph=graph,config=config) as session:
        old=session.run(old_y,{old_x:[2.,4.]})
    observe(cases,"compat_session_matches","feed the isolated TensorFlow 1.x compatible graph",
            [2.,4.],[[7.,13.],True],[old.tolist(),tf.executing_eagerly()])

    model=tf.keras.Sequential([tf.keras.Input(shape=(1,)),tf.keras.layers.Dense(
        1,kernel_initializer="zeros",bias_initializer="zeros")])
    model.compile(optimizer=tf.keras.optimizers.SGD(.25),loss="mse")
    inputs=tf.constant([[-1.],[1.]])
    targets=tf.constant([[-1.],[3.]])
    model.train_on_batch(inputs,targets)
    observe(cases,"keras_training_batch","run a training batch through Keras and check predictions",
            [[-1.],[1.]],[[-.5],[1.5]],model(inputs).numpy().tolist())

    module=tf.Module()
    module.compute=compiled
    with TemporaryDirectory(prefix="tf-graph-roundtrip-") as location:
        tf.saved_model.save(module,location,signatures={"serving_default":compiled.get_concrete_function()})
        loaded=tf.saved_model.load(location)
        answer=loaded.compute(x)
    observe(cases,"saved_model_round_trip","save and reload a traced function with its TensorFlow signature",
            [2.,4.],[7.,13.],answer.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-introduction-lab/compare-execution-modes.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 compare-execution-modes.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:TensorFlow

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a368.zip

下载课程关联工程包:TensorFlow

课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a359.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习