安装PyTorch的详细指南,涵盖不同操作系统和环境配置:
1. 官方推荐安装方法(最简单)
访问PyTorch官网获取最新安装命令:
PyTorch
选择您的配置后,网站会生成对应的安装命令。例如:
使用pip安装(CPU版本):
bash
pip install torch torchvision torchaudio
使用pip安装(CUDA 11.8 GPU版本):
bash
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
2. 各操作系统详细安装指南
Windows系统
GPU版本(需NVIDIA显卡):
-
确认已安装CUDA Toolkit
-
执行对应命令(示例为CUDA 11.8):
bash
-
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
CPU版本:
bash
pip3 install torch torchvision torchaudio
macOS系统
通用安装(M1/M2芯片推荐):
bash
pip3 install torch torchvision torchaudio
加速版本(Metal GPU支持):
bash
pip3 install --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cpu
Linux系统
使用conda安装:
bash
conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia
使用pip安装:
bash
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
3. 验证安装
安装完成后,运行以下Python代码验证:
python
import torch print(f"PyTorch版本: {torch.__version__}") print(f"CUDA可用: {torch.cuda.is_available()}") print(f"CUDA版本: {torch.version.cuda}") print(f"设备名称: {torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'CPU'}")
预期输出示例:
text
PyTorch版本: 2.0.1 CUDA可用: True CUDA版本: 11.8 设备名称: NVIDIA GeForce RTX 3090
4. 常见问题解决
版本兼容性问题
-
如果遇到版本冲突,建议创建虚拟环境:
bash
-
python -m venv pytorch_env source pytorch_env/bin/activate # Linux/macOS pytorch_env\Scripts\activate # Windows
下载速度慢
-
使用国内镜像源:
bash
-
pip install torch torchvision torchaudio -i https://pypi.tuna.tsinghua.edu.cn/simple
缺少CUDA驱动
-
确认NVIDIA驱动已安装:
bash
-
nvidia-smi
-
安装对应版本的CUDA Toolkit
5. 高级安装选项
源码编译安装
bash
git clone --recursive https://github.com/pytorch/pytorch cd pytorch python setup.py install
特定版本安装
bash
pip install torch==1.13.1 torchvision==0.14.1 torchaudio==0.13.1
6. 卸载PyTorch
bash
pip uninstall torch torchvision torchaudio conda uninstall pytorch torchvision torchaudio # 如果使用conda安装
建议根据您的硬件配置和项目需求选择合适的安装方式,GPU版本能显著加速深度学习训练过程,但需要兼容的NVIDIA显卡支持。