环境搭建
本章介绍如何安装和配置 TensorFlow 开发环境。
安装 TensorFlow
CPU 版本安装
对于没有 GPU 或只是学习的用户,安装 CPU 版本最简单:
pip install tensorflow
GPU 版本安装
如果需要使用 GPU 加速训练,需要额外安装 CUDA 和 cuDNN。
前提条件:
- NVIDIA GPU(计算能力 3.5 或更高)
- CUDA Toolkit
- cuDNN SDK
安装步骤:
-
查看 TensorFlow 与 CUDA 版本对应关系(参考 TensorFlow 官方文档)
-
安装 CUDA 和 cuDNN(以 TensorFlow 2.15 为例):
# 安装 CUDA 12.2
# 从 NVIDIA 官网下载安装
# 安装 cuDNN
# 从 NVIDIA 官网下载并解压到 CUDA 目录
- 安装 TensorFlow GPU 版本:
pip install tensorflow[and-cuda]
验证安装
import tensorflow as tf
# 查看 TensorFlow 版本
print("TensorFlow 版本:", tf.__version__)
# 检查 GPU 是否可用
print("GPU 是否可用:", len(tf.config.list_physical_devices('GPU')) > 0)
# 列出所有 GPU
gpus = tf.config.list_physical_devices('GPU')
for gpu in gpus:
print(gpu)
使用虚拟环境
推荐使用虚拟环境来管理 TensorFlow 项目,避免版本冲突。
使用 venv
# 创建虚拟环境
python -m venv tf-env
# 激活虚拟环境
# Windows:
tf-env\Scripts\activate
# Linux/macOS:
source tf-env/bin/activate
# 安装 TensorFlow
pip install tensorflow
使用 Conda
# 创建 conda 环境
conda create -n tf-env python=3.10
# 激活环境
conda activate tf-env
# 安装 TensorFlow
pip install tensorflow
GPU 内存管理
TensorFlow 默认会占用所有可用 GPU 内存,可以通过以下方式配置:
import tensorflow as tf
# 方式一:按需分配内存
gpus = tf.config.list_physical_devices('GPU')
if gpus:
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
# 方式二:限制 GPU 内存使用量
gpus = tf.config.list_physical_devices('GPU')
if gpus:
tf.config.set_logical_device_configuration(
gpus[0],
[tf.config.LogicalDeviceConfiguration(memory_limit=4096)]
)
开发工具推荐
Jupyter Notebook
适合交互式开发和实验:
pip install jupyter
jupyter notebook
VS Code
推荐安装以下扩展:
- Python
- TensorFlow Snippets
- Jupyter
Google Colab
免费提供 GPU 资源,适合学习和实验:
- 访问 Google Colab
- 在「运行时」→「更改运行时类型」中选择 GPU
- 直接运行 TensorFlow 代码
常见问题
1. CUDA 版本不匹配
Could not load dynamic library 'cudart64_XX.dll'
解决方案:确保安装的 CUDA 版本与 TensorFlow 版本匹配。查看 TensorFlow 官方文档 中的版本对应表。
2. 内存不足错误
ResourceExhaustedError: OOM when allocating tensor
解决方案:
- 减小 batch size
- 使用混合精度训练
- 配置 GPU 内存按需分配
3. DLL 加载失败(Windows)
ImportError: DLL load failed
解决方案:
- 安装 Visual C++ Redistributable
- 确保 CUDA 和 cuDNN 正确安装
完整环境配置示例
# 创建项目目录
mkdir tf-project && cd tf-project
# 创建虚拟环境
python -m venv venv
# 激活虚拟环境
# Windows:
venv\Scripts\activate
# Linux/macOS:
source venv/bin/activate
# 升级 pip
pip install --upgrade pip
# 安装 TensorFlow
pip install tensorflow
# 安装常用库
pip install numpy pandas matplotlib scikit-learn
# 安装 Jupyter
pip install jupyter
# 验证安装
python -c "import tensorflow as tf; print(tf.__version__)"
小结
本章介绍了 TensorFlow 的安装和环境配置。对于初学者,建议先使用 CPU 版本或 Google Colab 进行学习,熟悉后再配置 GPU 环境。下一章我们将学习 TensorFlow 的张量操作。