TensorFlow 环境搭建
选择匹配的平台和 Python 版本,在本地独立 CPU 环境验证包、运算及配置。
学完这一章,你能够
- 选择匹配的平台和 Python 版本,在本地独立 CPU 环境验证包、运算及配置。
先选版本与平台,再选安装器
先对照所选 TensorFlow 发布文件、Python 小版本、系统和架构,再安装。查看 python --version 和 python -m pip --version,确认 pip 归属同一个解释器。Python.org 安装器可配置 PATH。Anaconda 可提供完整软件组合,Miniconda 适合从更小环境开始。apt、Homebrew 和 Chocolatey 的用法受各平台约束。
单独管理依赖和工具
用 python -m venv 创建独立目录,Windows 可以直接运行该目录 Scripts/python.exe,Unix 通常使用 bin/python。也可用 Conda 创建并激活独立环境。分别查询已装包、导出版本和恢复。删除旧环境时要先退出并核对目录。
本站用 Windows x64、Python 3.12.14、TensorFlow 2.21.0 的原生 CPU wheel,按官方哈希核对后用本地 wheel 安装。适合学习和小型推理。官方 wheel 以 PyPI 为准,可先选具体版本;夜间构建另用临时环境测试。独立环境里用 python -m pip check 复核依赖。
Jupyter Notebook 或 Lab 需要选到实际装有 TensorFlow 的内核。旧 nbextensions 与新版 Notebook、Lab 的兼容性需查各自文档。VS Code、PyCharm 可绑定课程解释器并用调试器。Colab 的运行资源受配额和可用性影响。按需安装 NumPy、Pandas、Matplotlib、Seaborn、SciPy、Scikit-learn、Pillow、OpenCV、tqdm 并锁定版本。
区分 Windows CPU 和可用 GPU 的配置
TensorFlow 2.10 是官方原生 Windows CUDA 路线的最后一版。后续版本在 Windows 可按官方支持走 WSL2,Linux GPU 路线另查驱动、设备能力与包版本。nvidia-smi 可查驱动,nvcc 可查工具链;设备枚举还要与实际 TensorFlow 解释器交叉检查。显存需求按模型、精度与批大小而定。下载的 CUDA 与 cuDNN 版本应按所选发布版配置。
运行安装探针时先验证版本、解释器和可见设备,然后执行张量计算。本站 CPU 基准把数据创建放在计时前,先预热,每次读取计算结果后再记录耗时。GPU 速度和显存分支在 CPU 环境保留待处理。
排查依赖、内核与运行参数
超时先检查网络和包源响应。权限或依赖冲突可在新目录重建环境;用户目录安装不能修复网络超时。内核不可见时在指定环境装 ipykernel 并注册,随后重新选择内核。GPU 未识别时依次核对硬件、驱动、编译支持和运行时枚举。
按需选择显存增长或逻辑设备上限,且通常要在设备初始化前设置。旧 mixed_precision.experimental 例应迁移到公开的 set_global_policy,混合精度不保证 CPU 更快。XLA 可使用 autoclustering 配置或显式编译函数,支持范围和速度均要实测。项目升级前锁住依赖,在新环境复跑,再移交 requirements 或 Conda 环境文件。
Python 与 TensorFlow 的版本搭配
| 来源区间 | 按实际发布版本判断 |
| 2.15 与后续 | 2.15.0 官方测试范围是 Python 3.9 至 3.11。本站实际运行 2.21.0 与 Python 3.12.14。 |
| 2.12 至 2.14 | 2.12、2.13 可查 3.8 至 3.11,2.14.0 的测试范围从 3.9 起。 |
| 2.8 至 2.11 | 官方测试配置列出 Python 3.7 至 3.10;设备支持还要区分 2.10 与 2.11。 |
旧 CUDA 表应按明确版本阅读
| 来源区间 | CUDA | cuDNN |
| 2.15.0 和 2.21.0 | 官方 Linux 构建配置分别为 12.2 与 12.5。 | 官方列出的版本分别为 8.9 与 9.3。 |
| 2.12.0、2.13.0、2.14.0 | Linux 测试配置均列 11.8。 | 2.12、2.13 为 8.6,2.14 为 8.7。 |
验证独立 CPU 环境并同步测量矩阵乘法
展开查看收起
"""Validate a local TensorFlow CPU environment and document what CPU can measure."""
from importlib.metadata import version
from pathlib import Path
from statistics import median
import subprocess
import sys
from time import perf_counter
import json
import platform
import tensorflow as tf
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)))
def observe(cases,name,operation,inputs,expected,actual):
assert expected==actual,(name,expected,actual)
cases.append(dict(name=name,operation=operation,inputs=inputs,expected=expected,actual=actual,passed=True))
def main():
cases=[]
observe(cases,"verify_python_and_tf_versions","read the interpreter, TensorFlow and Keras versions",
{"interpreter":"project CPU environment"},["3.12.14","2.21.0","3.15.1"],
[platform.python_version(),tf.__version__,tf.keras.__version__])
observe(cases,"confirmed_isolated_python","verify that TensorFlow is installed beneath the independent interpreter",
{"entry":"sys.executable"},[True,True],[sys.prefix!=sys.base_prefix,
Path(tf.__file__).resolve().is_relative_to(Path(sys.prefix).resolve())])
command=[sys.executable,"-m","pip","--isolated","--disable-pip-version-check"]
checks=subprocess.run([*command,"check"],check=True,capture_output=True,text=True,timeout=30)
recorded=subprocess.run([*command,"freeze"],check=True,capture_output=True,text=True,timeout=30)
normalized=recorded.stdout.lower().splitlines()
observe(cases,"installed_dependency_snapshot","run pip check and verify frozen TensorFlow/Keras metadata",
["tensorflow","keras"],[True,True,True],["No broken requirements" in checks.stdout,
"tensorflow==2.21.0" in normalized,"keras==3.15.1" in normalized])
cases[-1]["observed_package_versions"]={name:version(name) for name in ("tensorflow","keras","numpy","h5py")}
with tf.device("/CPU:0"):
result=tf.constant([1,2,3])+tf.constant([4,5,6])
observe(cases,"local_cpu_computation","compute values and verify the actual tensor placement",
[[1,2,3],[4,5,6]],[[5,7,9],True],[result.numpy().tolist(),result.device.endswith("CPU:0")])
inputs=tf.ones((128,128))
for _ in range(3):
tf.matmul(inputs,inputs).numpy()
timings=[]
for _ in range(5):
t=perf_counter()
output=tf.matmul(inputs,inputs).numpy()
timings.append(perf_counter()-t)
observe(cases,"cpu_benchmark_materializes_results","measure five synchronous products after three CPU warmups",
{"size":128,"warmups":3,"repetitions":5},[[128,128],128.,True],
[list(output.shape),float(output[0,-1]),median(timings)>0])
cases[-1]["observed_median_seconds"]=median(timings)
observe(cases,"native_windows_device_capabilities","enumerate installed CPU/GPU devices and the CUDA build flag",
{"tensorflow":"2.21.0","platform":"Windows native"},[True,False,0],
[bool(tf.config.list_physical_devices("CPU")),bool(tf.test.is_built_with_cuda()),len(tf.config.list_physical_devices("GPU"))])
original=tf.keras.mixed_precision.global_policy()
old=tf.config.optimizer.get_jit()
try:
tf.keras.mixed_precision.set_global_policy("mixed_float16")
layer=tf.keras.layers.Dense(1,kernel_initializer="ones")
answer=layer(tf.constant([[2.,3.]]))
tf.config.optimizer.set_jit("autoclustering")
observe(cases,"modern_mixed_precision_configuration","run a mixed-precision layer and read the optimizer configuration",
{"inputs":[2,3],"policy":"mixed_float16"},["float16","float32",5.,"autoclustering"],
[answer.dtype.name,str(layer.kernel.dtype),float(answer.numpy()[0,0]),tf.config.optimizer.get_jit()])
finally:
tf.keras.mixed_precision.set_global_policy(original)
tf.config.optimizer.set_jit(old if old else False)
finish(cases)
if __name__=="__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 运行本站程序。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
比较 Notebook 内核的 sys.executable 和安装 TensorFlow 时使用的解释器。