一、为什么你的 PyTorch 安装会失败?(常见错误分析)

1. 包名拼写错误

  • 典型错误ERROR: Could not find a version for troch
  • 原因:误将 torch 拼成 troch(少了一个 r)。
  • 解决方案
    # 正确包名是 torch!
    pip install torch
    

2. 镜像源不受信任

  • 典型错误WARNING: The repository located at mirrors.aliyun.com is not trusted
  • 原因:使用 HTTP 镜像源时未添加信任参数。
  • 解决方案
    # 方法1:改用 HTTPS 镜像源(推荐)
    pip install torch -i https://mirrors.aliyun.com/pypi/simple/
    
    # 方法2:临时信任 HTTP 源(仅测试环境使用)
    pip install torch --trusted-host mirrors.aliyun.com -i http://mirrors.aliyun.com/pypi/simple/
    

3. 版本不兼容

  • 典型错误No matching distribution found for torch
  • 原因:Python 版本过低或操作系统不支持。
  • 检查项
    • Python 版本 ≥ 3.7(PyTorch 最低要求)
    • 确认操作系统(Windows/Linux/macOS)与包兼容。

二、最佳安装实践:官方推荐命令解析

1. 访问 PyTorch 官网生成命令

访问 PyTorch 官方安装指南,选择你的环境组合:

  • 操作系统(Windows/Linux/macOS)
  • 包管理工具(pip/conda)
  • CUDA 版本(GPU 用户)或 CPU 版本

2. 示例命令(CUDA 12.1 环境)

pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
  • 参数解析
    • torch:核心库
    • torchvision:计算机视觉扩展
    • torchaudio:音频处理扩展
    • --index-url:指定 PyTorch 官方 CUDA 镜像源

3. 验证安装

import torch
print(torch.__version__)            # 输出版本号,如 2.2.1
print(torch.cuda.is_available())    # 输出 True 表示 GPU 可用

三、镜像加速:让 pip 安装速度飞起来

1. 临时使用镜像源

# 阿里云镜像(国内推荐)
pip install torch -i https://mirrors.aliyun.com/pypi/simple/

# 清华大学镜像
pip install torch -i https://pypi.tuna.tsinghua.edu.cn/simple/

2. 永久配置镜像源

  • Linux/macOS:创建 ~/.pip/pip.conf
  • Windows:创建 C:\Users\<用户名>\pip\pip.ini
  • 添加内容
    [global]
    index-url = https://mirrors.aliyun.com/pypi/simple/
    trusted-host = mirrors.aliyun.com
    

四、疑难解答(FAQ)

Q1:安装后导入 torch 报错 DLL load failed

  • 原因:CUDA 版本与 PyTorch 不匹配。
  • 解决:卸载后重新安装对应 CUDA 版本的 PyTorch。

Q2:Conda 和 pip 混用导致冲突

  • 建议:优先使用单一工具管理环境,例如:
    conda create -n pytorch_env python=3.10
    conda activate pytorch_env
    conda install pytorch torchvision torchaudio pytorch-cuda=12.1 -c pytorch -c nvidia
    

Q3:如何彻底卸载 PyTorch?

pip uninstall torch torchvision torchaudio
# 手动删除残留文件(Windows:AppData/Local;Linux:~/.local)
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐