linux

如何在Linux上安装PyTorch

小樊
46
2025-04-25 20:05:38
栏目: 智能运维

在Linux上安装PyTorch的步骤如下:

方法一:使用pip安装

  1. 更新pip

    pip install --upgrade pip
    
  2. 安装PyTorch: 根据你的CUDA版本选择合适的命令。你可以在PyTorch官网找到最新的安装命令。

    • CPU版本

      pip install torch torchvision torchaudio
      
    • GPU版本(CUDA 11.3)

      pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113
      
    • GPU版本(CUDA 11.7)

      pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu117
      
    • GPU版本(CUDA 10.2)

      pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu102
      
    • GPU版本(CUDA 9.0)

      pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu90
      
    • CPU版本(无CUDA)

      pip install torch torchvision torchaudio
      

方法二:使用conda安装

如果你使用Anaconda或Miniconda,可以通过conda来安装PyTorch。

  1. 更新conda

    conda update conda
    
  2. 创建新的conda环境(可选)

    conda create -n pytorch_env python=3.8
    conda activate pytorch_env
    
  3. 安装PyTorch: 根据你的CUDA版本选择合适的命令。你可以在PyTorch官网找到最新的安装命令。

    • CPU版本

      conda install pytorch torchvision torchaudio cpuonly -c pytorch
      
    • GPU版本(CUDA 11.3)

      conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch
      
    • GPU版本(CUDA 11.7)

      conda install pytorch torchvision torchaudio cudatoolkit=11.7 -c pytorch
      
    • GPU版本(CUDA 10.2)

      conda install pytorch torchvision torchaudio cudatoolkit=10.2 -c pytorch
      
    • GPU版本(CUDA 9.0)

      conda install pytorch torchvision torchaudio cudatoolkit=9.0 -c pytorch
      

验证安装

安装完成后,你可以通过以下命令验证PyTorch是否安装成功:

import torch
print(torch.__version__)
print(torch.cuda.is_available())  # 如果安装了GPU版本,应该返回True

如果一切正常,你应该能够看到PyTorch的版本号,并且torch.cuda.is_available()会返回True(如果你安装的是GPU版本)。

希望这些步骤能帮助你在Linux上成功安装PyTorch!

0
看了该问题的人还看了