方法一:使用 pip 安装
安装 CPU 版本(无 GPU 支持):
bash
pip install torch==1.13.0 torchvision==0.14.0 torchaudio==0.13.0 --index-url https://download.pytorch.org/whl/cpu安装 GPU 版本(CUDA 11.7):
bash
pip install torch==1.13.0 torchvision==0.14.0 torchaudio==0.13.0 --index-url https://download.pytorch.org/whl/cu117安装 GPU 版本(CUDA 11.6):
bash
pip install torch==1.13.0 torchvision==0.14.0 torchaudio==0.13.0 --index-url https://download.pytorch.org/whl/cu116方法二:使用 conda 安装
安装 CPU 版本:
bash
conda install pytorch==1.13.0 torchvision==0.14.0 torchaudio==0.13.0 cpuonly -c pytorch安装 GPU 版本(CUDA 11.7):
bash
conda install pytorch==1.13.0 torchvision==0.14.0 torchaudio==0.13.0 pytorch-cuda=11.7 -c pytorch -c nvidia💡 如何选择版本?
检查你的系统是否有 NVIDIA GPU
按
Win + X,选择"设备管理器"展开"显示适配器"
如果有 NVIDIA 开头的设备,说明你有 NVIDIA GPU
检查 CUDA 版本(如果有 GPU)
bash
nvidia-smi在输出中查看 CUDA Version。
选择建议:
没有 NVIDIA GPU → 安装 CPU 版本
有 NVIDIA GPU,CUDA ≥ 11.0 → 安装 CUDA 11.7 版本
不确定或新手 → 安装 CPU 版本(更简单稳定)
📝 验证安装的完整代码
安装完成后,使用以下代码验证:
python
import torch
import torchaudio
print("PyTorch版本:", torch.__version__)
print("Torchaudio版本:", torchaudio.__version__)
print("CUDA是否可用:", torch.cuda.is_available())
# 测试基本功能
x = torch.rand(2, 3)
print("随机张量:")
print(x)
# 如果有GPU,测试GPU功能
if torch.cuda.is_available():
device = torch.device("cuda")
x_gpu = x.to(device)
print("GPU张量:")
print(x_gpu)
print("当前GPU:", torch.cuda.get_device_name(0))🌟 最新版本安装(可选)
如果你想要安装更新的版本而不是严格的 1.13.0,可以使用:
最新 CPU 版本:
bash
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu最新 GPU 版本(CUDA 12.1):
bash
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121