温馨提示×

ubuntu pytorch怎么配置

小樊
63
2026-09-17 00:13:23
栏目: 智能运维

在 Ubuntu 上配置 PyTorch,一般按下面步骤来,适合大多数情况(CPU / NVIDIA GPU)。


一、准备环境(推荐用 conda 或 venv)

方式 1:使用 Conda(最简单,推荐)

# 安装 Miniconda(如已安装可跳过)
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh

创建环境:

conda create -n torch python=3.10
conda activate torch

方式 2:使用 venv(系统 Python)

sudo apt update
sudo apt install python3-venv python3-pip
python3 -m venv torch_env
source torch_env/bin/activate

二、安装 PyTorch

✅ CPU 版本

pip install torch torchvision torchaudio

✅ GPU 版本(NVIDIA,需 CUDA)

先确认显卡驱动:

nvidia-smi

然后到官网选择对应命令(示例 CUDA 12.1):

pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121

常见 CUDA 版本:cu118 / cu121 / cu124


三、验证安装

import torch
print(torch.__version__)
print(torch.cuda.is_available())  # GPU 应为 True

四、常见问题

1. 找不到 CUDA

  • 确认 nvidia-smi 正常
  • 驱动版本 ≥ CUDA 要求
  • 使用正确的 cuXXX 安装命令

2. pip 太慢

pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

3. Jupyter 使用

pip install jupyter
jupyter notebook

五、最小示例

import torch

x = torch.randn(3, 3)
print(x)
print("CUDA:", torch.cuda.is_available())

如果你告诉我:

  • Ubuntu 版本
  • 是否有 NVIDIA 显卡
  • Python 版本

我可以给你精确的一条安装命令。

0 踩