TensorFlow — Google 全栈机器学习框架
Google 开源机器学习框架。TensorFlow 2.21(2026 年 3 月)、约 19.7 万星、Apache 2.0。Eager 执行、Keras、TPU 支持、端到端生态。
TensorFlow 是 Google 的开源机器学习框架——一个覆盖数据加载、模型训练、生产部署的端到端平台。2015 年 11 月 9 日由 Google Brain 团队首次发布。用 Python、C++ 和 CUDA 编写。最新版本:2.21.0(2026 年 3 月),GitHub 约 19.7 万星,Apache 2.0 许可。
TensorFlow 的独特之处#
TensorFlow 不只是训练库——它是一个生态系统:
| 组件 | 作用 |
|---|---|
| 核心框架 | 张量运算、eager 执行、XLA 编译器 |
| Keras | 高层模型构建 API |
| tf.data | 可扩展数据管道 |
| TensorFlow Serving | 生产模型服务(REST/gRPC) |
| LiteRT | 端侧推理(移动端、嵌入式) |
| TensorFlow.js | 浏览器内 ML(WebGPU/WASM) |
| TFX | 端到端生产 ML 管道 |
| XLA | 面向 GPU/TPU 的图编译器 |
核心概念#
张量#
一切都是张量——多维数组:
import tensorflow as tf
x = tf.constant([[1, 2], [3, 4]], dtype=tf.float32)
y = tf.matmul(x, x) # 矩阵乘法
print(y.shape) # (2, 2)pythonEager 执行#
TF 2.x 默认即时执行运算(像普通 Python)——易于调试。静态图 API 放在 tf.compat 中供旧代码使用。
XLA 编译器#
@tf.function(jit_compile=True)
def compute(x, w):
return tf.matmul(x, w)pythontf.function 把代码追踪成图,然后 XLA(Accelerated Linear Algebra)为 GPU/TPU 编译并融合算子——计算密集模型常获得 5-50 倍加速。
历史#
| 版本 | 年份 | 变化 |
|---|---|---|
| TF 1.x | 2015 | 静态计算图、session.run() |
| TF 2.0 | 2019 | eager 执行为默认、集成 Keras |
| TF 2.16-2.20 | 2024-2025 | Keras 3 后端、支持 Python 3.13 |
| TF 2.21 | 2026 年 3 月 | 最新稳定版 |
快速开始#
pip install tensorflow # CPU + GPU(NVIDIA CUDA)
pip install tensorflow-cpu # 仅 CPU,小得多bashimport tensorflow as tf
from tensorflow import keras
# 加载数据
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
# 构建模型
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation="relu"),
keras.layers.Dense(10, activation="softmax"),
])
# 训练
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy",
metrics=["accuracy"])
model.fit(x_train, y_train, epochs=5, validation_split=0.2)
# 保存
model.save("mnist.keras")pythonGPU 与 TPU 支持#
- GPU: 原生支持 NVIDIA CUDA;DirectX 和 macOS Metal 通过设备插件
- TPU: TensorFlow 是 Google TPU(张量处理单元)的参考框架——XLA 就是为它们构建的。这是 TensorFlow 仍大幅领先 PyTorch 的地方
- 分布式训练:
tf.distribute(MirroredStrategy、MultiWorkerMirroredStrategy、TPUStrategy)
谁在使用#
- YouTube 推荐引擎
- Waymo 自动驾驶车队
- Google 规模的 TPU 训练(Gemini 用 JAX + TensorFlow 混合训练)
- 依赖 TFX + TensorFlow Serving 的大型生产栈
优势与不足(2026)#
优势:
- 成熟的生产生态(Serving、TFX、LiteRT)——全球部署最多的 ML 运行时
- 最好的 TPU 支持和成熟的 XLA
- Keras 3 让模型也能跑在 PyTorch 或 JAX 后端上
- 19.7 万星、Google 背书、庞大维护力量
不足:
- 研究领域份额流失——PyTorch 已占论文 55% 以上
- Hugging Face 工具链 PyTorch 优先;TF 权重常被自动转换
- 遗留的静态图 API 仍带来复杂性
- Python API 安装包巨大(GPU wheel 约 570 MB)
结论#
TensorFlow 仍是生产主力:驱动着世界上最大的 ML 系统,独占移动端(LiteRT)、浏览器端(TF.js)和 TPU 领域。新研究用 PyTorch;而 Google 云、TPU、端侧和大规模服务场景,TensorFlow 依然是最稳妥的选择——Keras 3 还能让你彻底规避框架锁定。