我来帮你整理在 Ubuntu 24 上开始学习 PyTorch 的完整指南。
🚀 Ubuntu 24.04 上 PyTorch 初学指南
1. 环境准备
检查 NVIDIA 显卡(如需 GPU 支持)
bash
# 查看显卡信息
nvidia-smi
# 检查 CUDA 版本
nvcc --version
安装基础依赖
bash
sudo apt update && sudo apt upgrade -y
sudo apt install python3 python3-pip python3-venv -y
2. 创建虚拟环境(推荐)
bash
# 创建项目目录
mkdir ~/pytorch-learning && cd ~/pytorch-learning
# 创建虚拟环境
python3 -m venv venv
# 激活环境
source venv/bin/activate
# 升级 pip
pip install --upgrade pip
3. 安装 PyTorch
根据你的硬件选择安装方式:
有 NVIDIA GPU(推荐 CUDA 12.4)
bash
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124
仅 CPU 版本
bash
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
验证安装
python
import torch
print(f"PyTorch 版本: {torch.__version__}")
if torch.cuda.is_available():
print(f"CUDA 可用: {torch.cuda.is_available()}")
print(f"CUDA 版本: {torch.version.cuda}")
print(f"GPU: {torch.cuda.get_device_name(0)}")
else:
print(f"CPU 线程数: {torch.get_num_threads()}")
print(f"是否支持 MKL: {torch.backends.mkl.is_available()}")
# 简单测试
x = torch.rand(5, 3)
print(x)
4. 安装常用工具包
bash
pip install numpy matplotlib jupyterlab tensorboard
5. 第一个 PyTorch 程序
创建 first_pytorch.py:
python
import torch
import torch.nn as nn
# 创建张量
x = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
print("张量 x:", x)
# 自动求导示例
x = torch.tensor(2.0, requires_grad=True)
y = x ** 3 + 2 * x
y.backward()
print(f"函数 y = x³ + 2x 在 x=2 处的导数: {x.grad}") # 输出: 14.0
# 简单神经网络
class Net(nn.Module):
def __init__(self):
super().__init__()
self.fc = nn.Linear(10, 1)
def forward(self, x):
return self.fc(x)
model = Net()
print(model)
运行:
bash
python first_pytorch.py
6. 启动 JupyterLab(推荐学习方式)
bash
jupyter lab --ip=0.0.0.0 --port=8888
7. 学习资源推荐
| 资源 | 链接 |
|---|---|
| 官方教程 | https://pytorch.org/tutorials/ |
| 官方文档 | https://pytorch.org/docs/stable/ |
| 60分钟入门 | https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html |
8. 常见问题解决
问题:CUDA 版本不匹配
bash
# 查看系统 CUDA 版本
cat /usr/local/cuda/version.json # 或 nvidia-smi 显示的 CUDA Version
# 安装对应版本 PyTorch(如 CUDA 11.8)
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
问题:权限不足
bash
# 避免使用 sudo pip,改用用户安装
pip install --user torch
问题:Jupyter 找不到虚拟环境内核
bash
pip install ipykernel
python -m ipykernel install --user --name=pytorch-env