Python 深度学习环境配置指南:PyTorch 安装、源配置、GPU 检查及 matplotlib 使用
前言
在 Python 深度学习开发中,常会遇到包下载慢、PyTorch 安装报错、GPU 是否可用验证、可视化库安装等基础问题。本文汇总了实际操作中高频问题的解决方案,涵盖 pip 源配置、PyTorch 安装(含清华源适配)、GPU 可用性检查、matplotlib(plt)安装与使用,适用于新手快速搭建开发环境。
一、pip 默认源更换为清华源(解决下载慢问题)
国内使用默认 pip 源(国外服务器)下载包时速度较慢,将默认源改为清华源可显著提升下载效率,支持永久配置和临时使用两种方式。
1.1 永久配置(推荐)
(1)Linux/macOS 系统
- 打开终端,创建 pip 配置目录(若已存在则跳过):
mkdir -p ~/.config/pip
- 编辑配置文件(使用 nano 或 vim 编辑器):
nano ~/.config/pip/pip.conf
- 粘贴以下内容,保存并退出(nano 按 Ctrl+O 保存,Ctrl+X 退出):
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple # 清华源地址
[install]
trusted-host = pypi.tuna.tsinghua.edu.cn # 信任该源(避免 SSL 验证报错)
(2)Windows 系统
- 打开文件管理器,在地址栏输入%APPDATA%,按回车进入 Roaming 目录;
- 在 Roaming 目录下新建 pip 文件夹(若已存在则跳过);
- 在 pip 文件夹内新建 pip.ini 文件(注意后缀为.ini,而非.txt);
- 用记事本打开 pip.ini,粘贴以下内容并保存:
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host = pypi.tuna.tsinghua.edu.cn
1.2 临时使用(单次生效)
若无需永久修改,可在每次 pip install 时通过-i 参数指定清华源,示例:
pip install 包名 -i https://pypi.tuna.tsinghua.edu.cn/simple
1.3 配置验证
安装任意包(如 numpy),查看终端输出,若显示以下内容则源配置生效:
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
二、PyTorch 安装(含清华源适配与报错解决)
PyTorch 安装需匹配CUDA 版本(GPU 用户)或选择 CPU 版本,常见问题为'找不到兼容版本',以下是完整解决方案。
2.1 需求场景:将官方命令改为清华源
原官方安装命令(指定 CUDA 12.8):
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu128

