深度学习环境配置是入门的第一道门槛。本文将从零开始,详细介绍 Conda 和 pip 两种方式配置 PyTorch / TensorFlow 环境,涵盖 CPU 和 GPU 版本,以及常见问题排查。
资源下载 :Anaconda3 安装包(百度网盘) 提取码: 6xee
1. 前置准备:NVIDIA 驱动与 CUDA
重要概念澄清 :很多人混淆了 NVIDIA 驱动 、CUDA Toolkit 和 cuDNN ,这里统一说明:
组件
作用
谁需要装
NVIDIA 驱动
让操作系统识别显卡
有独显就必须装
CUDA Toolkit
GPU 通用计算工具包
PyTorch/TensorFlow GPU 版需要
cuDNN
深度学习加速库
GPU 版框架需要
Conda 安装 PyTorch 时会自动处理 CUDA Toolkit 和 cuDNN,无需手动安装。
1.1 检查显卡驱动
如果能正常输出显卡信息(如 RTX 3060、RTX 4090 等),说明驱动已安装。右上角的 CUDA Version 表示驱动支持的最高 CUDA 版本。
如果没有安装驱动:
Windows :前往 NVIDIA 驱动下载 ,选择对应显卡型号下载安装
Linux :1 2 3 sudo apt updatesudo apt install nvidia-driver-535 sudo reboot
如果使用 Conda 安装 PyTorch,可以跳过此步,Conda 会自动处理。
前往 CUDA Toolkit 下载页 下载对应版本。
Windows :下载 .exe 安装包,一路 Next。
Linux :
1 2 3 wget https://developer.download.nvidia.com/compute/cuda/11.8.0/local_installers/cuda_11.8.0_520.61.05_linux.runsudo sh cuda_11.8.0_520.61.05_linux.run
安装完成后添加环境变量:
1 2 3 4 echo 'export PATH=/usr/local/cuda/bin:$PATH' >> ~/.bashrcecho 'export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH' >> ~/.bashrcsource ~/.bashrc
1.3 安装 cuDNN(可选)
同样,Conda 安装会自动处理,无需手动安装。
前往 cuDNN 下载页 (需注册 NVIDIA 账号),下载对应 CUDA 版本的 cuDNN。
1 2 3 4 sudo cp cudnn-*-archive/include/cudnn*.h /usr/local/cuda/includesudo cp cudnn-*-archive/lib/libcudnn* /usr/local/cuda/lib64sudo chmod a+r /usr/local/cuda/include/cudnn*.h /usr/local/cuda/lib64/libcudnn*
2. 方案一:使用 Conda 安装(推荐新手) Conda 是一个跨平台的包管理和环境管理工具,最大的优势是能自动处理 CUDA 和 cuDNN 依赖。
2.1 安装 Conda 有三个选择,按需安装:
选项 A:Miniconda(推荐,轻量级) 只包含 Python 和 Conda,体积小,按需安装其他包。
下载地址 :Miniconda 官网
Windows :下载 .exe 安装包,安装时勾选 “Add Miniconda to my PATH environment variable”
macOS :1 brew install --cask miniconda
Linux :1 2 wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh bash Miniconda3-latest-Linux-x86_64.sh
选项 B:Anaconda(全家桶,适合数据科学) 包含 Python + Conda + 250+ 常用数据科学包,体积较大(约 3GB),开箱即用。
下载地址 :Anaconda 官网
适合人群 :不想一个个装包、希望开箱即用的数据科学初学者
缺点 :体积大、预装包多(很多可能用不到)
选项 C:Mamba(Conda 加速版) Mamba 是 Conda 的 C++ 重写版本,命令与 Conda 完全兼容,但依赖解析速度提升 10-100 倍。
1 2 conda install -n base -c conda-forge mamba
之后所有 conda 命令替换为 mamba 即可:
1 2 3 mamba create -n dl_env python=3.10 -y mamba activate dl_env mamba install pytorch torchvision torchaudio pytorch-cuda=12.1 -c pytorch -c nvidia
验证安装:
1 2 3 conda --version mamba --version
2.2 配置 Conda 镜像源(国内用户必做) 1 2 3 4 5 6 conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch conda config --set show_channel_urls yes
2.3 创建虚拟环境 1 2 3 4 5 6 7 8 conda create -n dl_env python=3.10 -y conda activate dl_env python --version
2.4 安装 PyTorch 前往 PyTorch 官网 获取最新安装命令。
CPU 版本(无独显 / Mac 用户) 1 conda install pytorch torchvision torchaudio cpuonly -c pytorch
GPU 版本(有 NVIDIA 显卡) 1 2 3 4 5 conda install pytorch torchvision torchaudio pytorch-cuda=12.1 -c pytorch -c nvidia conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia
CUDA 版本选择 :nvidia-smi 显示的 CUDA Version 是驱动支持的最高版本,向下兼容。例如驱动显示 CUDA 12.4,可以安装 CUDA 12.1 的 PyTorch。
2.5 安装 TensorFlow 1 2 3 4 5 conda install tensorflow-gpu -c conda-forge conda install tensorflow -c conda-forge
3. 方案二:使用 pip 安装(适合进阶用户) 如果你不想用 Conda,或者在服务器上需要更轻量的环境,可以直接用 pip + venv。
3.1 安装 Python
Windows :前往 Python 官网 下载安装,安装时勾选 “Add Python to PATH”
macOS :brew install python@3.10
Linux :sudo apt install python3.10 python3.10-venv python3-pip
3.2 创建虚拟环境 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 python -m venv dl_env dl_env\Scripts\Activate.ps1source dl_env/Scripts/activatesource dl_env/bin/activate deactivate
3.3 配置 pip 镜像源(国内用户必做) 1 2 3 4 5 pip install torch -i https://pypi.tuna.tsinghua.edu.cn/simple pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
3.4 安装 PyTorch (pip) CPU 版本 1 pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
GPU 版本 1 2 3 4 5 pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121 pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
注意 :pip 安装 GPU 版 PyTorch 时,会自带 CUDA 运行时库,但需要系统已安装 NVIDIA 驱动。
3.5 安装 TensorFlow (pip) 1 2 3 4 5 pip install tensorflow[and-cuda] pip install tensorflow
TensorFlow + pip 的坑 :TensorFlow 对 CUDA 版本要求严格,必须精确匹配。建议参考 TensorFlow 官网 的版本对应表。
4. 验证安装 4.1 测试 PyTorch 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 import torchprint ("=" * 50 )print ("PyTorch 版本:" , torch.__version__)print ("CUDA 是否可用:" , torch.cuda.is_available())if torch.cuda.is_available(): print ("CUDA 版本:" , torch.version.cuda) print ("cuDNN 版本:" , torch.backends.cudnn.version()) print ("GPU 数量:" , torch.cuda.device_count()) print ("GPU 名称:" , torch.cuda.get_device_name(0 )) x = torch.rand(3 , 3 ).cuda() y = torch.rand(3 , 3 ).cuda() z = x @ y print ("\nGPU 张量运算测试:" ) print ("x:\n" , x) print ("y:\n" , y) print ("x @ y:\n" , z)else : print ("当前使用 CPU 模式" ) x = torch.rand(3 , 3 ) print ("CPU 张量运算测试:\n" , x @ x)print ("=" * 50 )
4.2 测试 TensorFlow 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import tensorflow as tfprint ("=" * 50 )print ("TensorFlow 版本:" , tf.__version__)print ("GPU 可用数量:" , len (tf.config.list_physical_devices('GPU' )))if tf.config.list_physical_devices('GPU' ): with tf.device('/GPU:0' ): a = tf.random.normal([3 , 3 ]) b = tf.random.normal([3 , 3 ]) c = tf.matmul(a, b) print ("GPU 张量运算测试:\n" , c.numpy())else : print ("当前使用 CPU 模式" )print ("=" * 50 )
4.3 综合测试脚本 保存为 test_env.py,一键验证所有组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 import sysprint ("=" * 60 )print (f"Python 版本: {sys.version} " )print ("-" * 60 )try : import torch print (f"PyTorch {torch.__version__} : OK" ) if torch.cuda.is_available(): print (f" -> CUDA {torch.version.cuda} , GPU: {torch.cuda.get_device_name(0 )} " ) else : print (" -> CPU 模式" )except ImportError: print ("PyTorch: 未安装" )try : import tensorflow as tf print (f"TensorFlow {tf.__version__} : OK" ) gpus = tf.config.list_physical_devices('GPU' ) print (f" -> GPU 数量: {len (gpus)} " )except ImportError: print ("TensorFlow: 未安装" )try : import numpy as np print (f"NumPy {np.__version__} : OK" )except ImportError: print ("NumPy: 未安装" )try : import cv2 print (f"OpenCV {cv2.__version__} : OK" )except ImportError: print ("OpenCV: 未安装" )print ("=" * 60 )
5. Conda 环境管理常用命令 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 conda env list conda create -n env_name python=3.10 -y conda activate env_name conda deactivate conda install numpy pandas matplotlib conda env export > environment.yml conda env create -f environment.yml conda env remove -n env_name conda list
6. 常见问题排查 6.1 torch.cuda.is_available() 返回 False 排查步骤:
1 2 3 4 5 6 7 8 9 nvidia-smi python -c "import torch; print(torch.version.cuda)" pip uninstall torch torchvision torchaudio -y pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
6.2 Conda 安装速度慢 1 2 3 4 5 conda install -n base -c conda-forge mamba mamba install pytorch torchvision torchaudio pytorch-cuda=12.1 -c pytorch -c nvidia
6.3 pip 安装超时 1 2 pip install torch --timeout 120 -i https://pypi.tuna.tsinghua.edu.cn/simple
6.4 CUDA 版本不匹配 1 RuntimeError: The NVIDIA driver on your system is too old
解决方案 :升级显卡驱动,或安装更低版本的 CUDA PyTorch。参考 PyTorch 历史版本 。
6.5 内存不足 (OOM) 1 2 3 4 5 6 7 8 torch.cuda.empty_cache() from torch.cuda.amp import autocast, GradScaler scaler = GradScaler()with autocast(): output = model(input )
6.6 Windows 上 conda activate 不生效 1 2 3 4 5 6 7 conda init powershell conda init bash
7. Conda vs pip 对比
特性
Conda
pip + venv
环境管理
内置,功能强大
需配合 venv
CUDA 管理
自动处理
需手动安装
包管理范围
Python + C/C++ 库
仅 Python 包
依赖解析
更严格,不易冲突
可能出现冲突
安装速度
较慢(可用 Mamba 加速)
较快
适用场景
数据科学、深度学习
Web 开发、轻量项目
建议 :
新手 / 数据科学 / 深度学习 -> Conda (或 Mamba)
进阶用户 / 服务器部署 / 只需要 PyTorch -> pip + venv
Mac 用户(Apple Silicon)-> Conda (对 ARM 架构支持更好)