TensorFlow 简介
对照 TensorFlow 的即时执行、函数图和早期会话方式,理解框架各组件的职责。
学完这一章,你能够
- 对照 TensorFlow 的即时执行、函数图和早期会话方式,理解框架各组件的职责。
张量、图与执行环境
TensorFlow 由 Google Brain 团队发起。张量有形状和类型,计算图把张量运算及其依赖组织成节点和边。TensorFlow 1.x 常以 Session 驱动图。2.x 默认即时执行,tf.function 可按输入签名追踪计算图。
辨认历史教程使用的接口
Google 的早期分布式系统 DistBelief 有 2012 年论文。TensorFlow 于 2015 年 11 月开源,1.0 于 2017 年 2 月发布,2.0 正式发布于 2019 年 9 月 30 日。阅读 1.x 示例时关注占位符、资源初始化和会话输入。迁移到 2.x 时优先使用即时张量、tf.function 和 Keras 组件。
按环境选择工具
Core 负责张量与求导。TensorBoard 负责记录和可视化。TensorFlow.js 面向浏览器或 Node.js。TensorFlow Lite 的现行端侧路线称 LiteRT。Serving 用于服务化,TFX 用于可复现流水线,TensorFlow Hub 用于发现已训练模块。CPU、GPU、TPU 和 C++、Java、Go 等接口的支持要查各自版本。向量化、分发策略、图优化与硬件收益需按负载测试。
框架能服务于图像、语言、语音和推荐模型,也能写线性或逻辑回归。支持向量机、决策树、K-means、层次聚类与 PCA 可从专门的传统机器学习库开始。强化学习另有环境和策略,科学用途可从模拟、优化、信号处理和频域分析入手。
要选择框架,可比较接口、部署目标、设备支持和维护成本。TensorFlow 与 PyTorch 是张量计算和训练框架,Scikit-learn 聚焦传统估计器、变换与评估,Keras 3 是可使用 TensorFlow 等后端的高层接口。旧表中的熟练程度和生态级别属于主观评级。
文献中已有 Google 服务使用 TensorFlow 的记录。来源列举了 Uber、Airbnb、Twitter、Intel 及其用例,具体项目和当前技术栈仍待逐一核实。行业例子包括医疗影像、风险与欺诈评估、零售推荐、制造质检和媒体检索。先掌握张量,再用 Keras 写小模型,最后处理项目训练、部署和性能。
选择框架时看哪些条件
| 问题 | TensorFlow | PyTorch | Scikit-learn | Keras |
| 先学什么 | 张量与 Keras 训练 | 张量与模块 | 估计器与数据划分 | 层、模型、训练入口 |
| 如何定制 | GradientTape、tf.function | autograd、Module | 组合估计器与变换 | 自定义 Layer 与训练步骤 |
| 模型交付 | SavedModel 及目标运行时 | 查目标平台导出约束 | 锁定版本和输入协议 | 依后端和导出格式而定 |
| 怎样确认支持 | 查官方文档、发布和问题 | 查同版本文档与论坛 | 查版本迁移和模块参考 | 结合后端支持矩阵 |
| 典型业务 | 张量计算、训练与预测 | 张量计算、训练与预测 | 传统分类、回归、聚类 | 深度学习建模接口 |
| 落地衡量 | 核对延迟、维护和扩展 | 核对部署可用性 | 核对模型服务与依赖 | 核对保存、推理和后端 |
比较即时图、兼容会话与保存后加载
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 运行本站程序。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
通常直接用即时执行,按需用 tf.function 追踪图。