PyTorch 是一个强大的开源深度学习框架,以其灵活性和动态计算图而广受欢迎。以下是 PyTorch 的详细教程,涵盖从基础到实际应用的使用方法。
1. 安装与导入
1.1 安装 PyTorch
访问 PyTorch 官方网站,根据系统、Python 版本和 CUDA 支持选择安装命令。
常用安装命令:
pip install torch torchvision torchaudio
1.2 导入库
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
2. PyTorch 基础
2.1 张量(Tensor)
张量是 PyTorch 的核心数据结构,可以看作是一个高维数组。
# 创建张量
a = torch.tensor([1.0, 2.0, 3.0])
b = torch.tensor([4.0, 5.0, 6.0])
# 基本运算
c = a + b
print(c) # 输出 tensor([5., 7., 9.])
# 随机张量
random_tensor = torch.rand((2, 3)) # 2行3列随机数
print(random_tensor)
输出结果
tensor([5., 7., 9.])
tensor([[0.9980, 0.2970, 0.5257],
[0.8807, 0.0471, 0.7896]])
2.2 自动求导
PyTorch 提供动态计算图支持自动求导。
x = torch.tensor(2.0, requires_grad=True)
y = x**2 + 3*x + 4
y.backward() # 自动求导
print(x.grad) # 输出 dy/dx = 2*x + 3 = 7.0
输出结果
tensor(7.)
3. 数据加载
PyTorch 提供强大的数据加载功能。
import torchvision.transforms as tran