温馨提示×

Linux PyTorch环境怎么配置

小樊
61
2025-04-23 19:50:01
栏目: 智能运维

在Linux系统上配置PyTorch环境可以分为几个主要步骤,具体取决于你是否需要使用GPU支持。以下是详细的安装步骤:

1. 安装Anaconda(推荐)

  • 更新系统包
sudo apt update && sudo apt upgrade -y
  • 安装Anaconda

访问Anaconda官网,下载适用于Linux的Anaconda安装包。在终端中导航到下载目录,运行安装脚本:

bash Anaconda3-2022.10-Linux-x86_64.sh

按照屏幕上的指示完成安装,并在 .bashrc 文件中添加Anaconda的路径。

2. 创建虚拟环境

conda create --name pytorch_env python=3.9

3. 激活虚拟环境

conda activate pytorch_env

4. 安装PyTorch

安装CPU版本

conda install pytorch torchvision torchaudio cpuonly -c pytorch

安装GPU版本(确保已安装CUDA和cuDNN)

conda install pytorch torchvision torchaudio cudatoolkit=11.8 -c pytorch -c nvidia

注意:请将 11.8 替换为你系统上安装的CUDA版本。

5. 验证安装

在Python解释器中运行以下代码:

import torch
print(torch.__version__)

检查CUDA是否可用:

print(torch.cuda.is_available())

如果输出为 True,则表示PyTorch已成功安装并可以使用GPU。

6. 使用清华镜像源加速安装(可选)

如果在安装过程中遇到网速慢的问题,可以配置清华镜像源来加速下载:

conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
conda config --set show_channel_urls yes
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/

7. 其他有用的操作

  • 查看显卡信息
nvidia-smi
  • 查看系统信息
lsb_release -a
  • 查看系统位数
file /bin/ls
  • 查看当前可获取的Python库的版本
pip list
  • 更新指定版本的Python库
pip install --upgrade package_name==version_number
  • 卸载所有的安装包
pip freeze > requirements.txt
pip uninstall -r requirements.txt -y

0