PyTorch 安装
PyTorch 安装指南
以下是如何在不同环境下安装 PyTorch 的简明指南。PyTorch 支持 Windows、macOS 和 Linux,并提供 CPU 和 GPU 版本。安装前,建议使用虚拟环境以避免依赖冲突。
1. 选择安装方式
PyTorch 可以通过 pip 或 conda 安装。推荐访问 PyTorch 官网 的“Get Started”页面,根据你的系统、Python 版本、CUDA 版本(如果使用 GPU)生成准确的安装命令。
2. 基本要求
- Python 版本:3.7 或更高(推荐 3.8+)。
- 操作系统:Windows、macOS、Linux。
- GPU(可选):需要 NVIDIA GPU 和兼容的 CUDA 工具包(例如,CUDA 11.8 或 12.1)。
- 虚拟环境(推荐):
python -m venv pytorch_env
source pytorch_env/bin/activate # Linux/macOS
pytorch_env\Scripts\activate # Windows
3. 使用 pip 安装
以下是常见的 pip 安装命令(以 Python 3.8+ 和 CUDA 11.8 为例):
CPU 版本
pip install torch torchvision torchaudio
GPU 版本(CUDA 11.8)
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
GPU 版本(CUDA 12.1)
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
- 说明:
torchvision
和torchaudio
是可选的,分别用于计算机视觉和音频任务。- 替换
cu118
或cu121
以匹配你的 CUDA 版本。如果不确定 CUDA 版本,运行nvidia-smi
检查。
4. 使用 conda 安装
如果你使用 Anaconda 或 Miniconda:
CPU 版本
conda install pytorch torchvision torchaudio cpuonly -c pytorch
GPU 版本(CUDA 11.8)
conda install pytorch torchvision torchaudio cudatoolkit=11.8 -c pytorch
5. 验证安装
安装完成后,验证 PyTorch 是否正常工作:
import torch
print(torch.__version__) # 输出 PyTorch 版本,例如 2.4.1
print(torch.cuda.is_available()) # 检查 GPU 可用性,True 表示 GPU 可用
6. 常见问题
- CUDA 版本不匹配:确保你的 NVIDIA 驱动支持所选 CUDA 版本。运行
nvidia-smi
检查驱动和 CUDA 兼容性。 - 安装缓慢:国内用户可使用镜像源,例如:
pip install torch -i https://pypi.tuna.tsinghua.edu.cn/simple
- ModuleNotFoundError:确认激活虚拟环境或检查 Python 版本兼容性。
7. 其他安装方式
- Docker:PyTorch 提供官方 Docker 镜像,适合需要隔离环境的用户:
docker pull pytorch/pytorch
- 源码安装:高级用户可从 PyTorch GitHub 克隆代码并编译。
8. 资源
- PyTorch 官网:https://pytorch.org/get-started/locally/
- 安装问题讨论:在 X 平台搜索 #PyTorch 或 #PyTorchInstall 获取社区帮助。
如果你遇到特定安装问题(例如,GPU 配置、环境冲突)或需要进一步指导,请提供更多细节,我可以帮你排查!