目录
torch.from_numpy() :从NumPy数组创建张量
torch.save(model.state_dict(), 'model.pth')
torch.save(model, 'model.pth')
对于只保存参数的方式,需要先定义相同的模型结构,然后使用 model.load_state_dict(torch.load('model.pth')) 加载模型参数
对于保存整个模型的方式,可以直接使用 torch.load('model.pth') 加载模型,然后将其分配给一个变量即可使用
PyTorch是一个功能强大的深度学习库,以下是其常用方法功能的分类介绍:
张量操作
创建张量:
torch.tensor() :直接从数据创建张量
torch.zeros() :创建全零张量
torch.ones() :创建全一张量
torch.randn() :创建正态分布随机张量
torch.arange() :创建等差序列张量
torch.linspace() :创建线性间隔张量
## 张量操作
# 创建张量
import torch
# 创建张量
tensor_from_data = torch.tensor([1, 2, 3])
zeros_tensor = torch.zeros((3, 3))
ones_tensor = torch.ones((2, 2))
randn_tensor = torch.randn((3, 3))
arange_tensor = torch.arange(0, 10)
linspace_tensor = torch.linspace(0, 10, steps=5)
print(tensor_from_data) # tensor([1, 2, 3])
print(zeros_tensor)
# tensor([[0., 0., 0.],
# [0., 0., 0.],
# [0., 0., 0.]])
print(ones_tensor)
# tensor([[1., 1.],
# [1., 1.]])
print(randn_tensor)
# tensor([[ 0.9779, 1.8636, -0.8193],
# [-0.8590, 0.4308, -0.2886],
# [-1.1653, 0.4701, -1.0421]])
print(arange_tensor) # tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
print(linspace_tensor) # tensor([ 0.0000, 2.5000, 5.0000, 7.5000, 10.0000])
张量属性:
tensor.shape :获取张量的形状
tensor.dtype :获取张量的数据类型
tensor.device :获取张量所在的设备
# 张量属性
print(tensor_from_data.shape) # 输出:torch.Size([3])
print(zeros_tensor.dtype) # 输出:torch.float32
print(ones_tensor.device) # 输出:cpu
张量转换:
tensor.to() :将张量转换到指定设备或数据类型
tensor.numpy() :将张量转换为NumPy数组
torch.from_numpy() :从NumPy数组创建张量
# 张量转换
tensor_to_cpu = tensor_from_data.to('cpu')
print(tensor_to_cpu) # tensor([1, 2, 3])
tensor_to_float = tensor_from_data.to(torch.float32)
print(tensor_to_float) # tensor([1., 2., 3.])
numpy_array = tensor_from_data.numpy()
print(numpy_array) # [1 2 3]
tensor_from_numpy = torch.from_numpy(numpy_array)
print(tensor_from_numpy) # tensor([1, 2, 3])
张量操作:
数学运算
支持加法 tensor1 + tensor2 、减法 tensor1 - tensor2 、乘法 tensor1 * tensor2 、除法 tensor1 / tensor2 等逐元素运算,以及矩阵乘法 torch.matmul(tensor1, tensor2)
广播机制
在进行张量运算时,会自动扩展较小张量的维度以匹配较大张量的维度,从而实现更灵活的运算
索引和切片
与NumPy类似,可以通过索引和切片操作来访问张量的特定元素或子张量
重塑和转置
tensor.reshape() 可以改变张量的形状, tensor.transpose() 可以对张量进行转置操作
# 张量操作
tensor1 = torch.tensor([1, 2, 3])
tensor2 = torch.tensor([4, 5, 6])
add_tensor = tensor1 + tensor2 # 加法
print(add_tensor) # tensor([5, 7, 9])
mul_tensor = tensor1 * tensor2 # 乘法
print(mul_tensor) # tensor([ 4, 10, 18])
matmul_tensor = torch.matmul(tensor1.unsqueeze(0), tensor2.unsqueeze(1)) # 矩阵乘法
print(matmul_tensor) # tensor([[32]])
reshaped_tensor = tensor_from_data.reshape((1, 3)) # 重塑
print(reshaped_tensor) # tensor([[1, 2, 3]])
transposed_tensor = tensor_from_data.reshape((3, 1)).transpose(0, 1) # 转置
print(transposed_tensor) # tensor([[1, 2, 3]])
自动求导
自动求导机制
PyTorch的 autograd 模块能够自动计算梯度,这对于神经网络的反向传播至关重要。当创建张量时,设置 requires_grad=True ,则该张量的所有操作都会被跟踪,以便后续计算梯度
## 自动求导
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
y = x * x
y.sum().backward() # 反向传播
print(x.grad) # 输出梯度 [2., 4., 6.]
定义新自动求导函数
可以通过继承 torch.autograd.Function 类并实现 forward 和 backward 方法来定义新的自动求导函数,从而实现自定义的梯度计算逻辑
# 定义新自动求导函数
class CustomReLU(torch.autograd.Function):
@staticmethod # 表示这是一个静态方法,不需要实例化类就可以调用
def forward(ctx, input):
ctx.save_for_backward(input) # 保存输入张量,以便在反向传播时使用
return torch.relu(input) # 前向传播:应用 ReLU 激活函数
@staticmethod
def backward(ctx, grad_output):
input, = ctx.saved_tensors # 获取保存的输入张量
grad_input = grad_output.clone() # 创建一个与 grad_output 形状相同的张量
grad_input[input < 0] = 0 # 对于输入小于0的部分,梯度为0
return grad_input # 返回梯度
custom_relu = CustomReLU.apply
x = torch.tensor([-1.0, 2.0, 3.0], requires_grad=True)
y = custom_relu(x)
y.sum().backward()
print(x.grad) # 输出梯度 [0., 1., 1.]
神经网络构建
torch.nn 模块:
层定义
提供了各种神经网络层的实现如 nn.Linear 定义全连接层, nn.Conv2d 定义二维卷积层, nn.BatchNorm2d 定义二维批量归一化层等
激活函数
包括 torch.relu 、 torch.sigmoid 、 torch.tanh 等常用的激活函数
损失函数
提供了多种损失函数,如 nn.MSELoss 用于均方误差损失, nn.CrossEntropyLoss 用于分类任务的交叉熵损失, nn.BCELoss 用于二分类任务的二元交叉熵损失等
优化器
实现了多种优化算法,如 torch.optim.SGD 是随机梯度下降优化器, torch.optim.Adam 是Adam优化器等,用于更新网络参数
模型定义:
通过继承 torch.nn.Module 类来定义自己的神经网络模型,在 __init__ 方法中定义网络的层,在 forward 方法中定义数据在网络中的前向传播过程
## 神经网络构建
import torch.nn as nn
import torch.optim as optim
# 定义模型
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.fc1 = nn.Linear(10, 5)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(5, 2)
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
model = MyModel()
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
# 模拟训练
inputs = torch.randn(4, 10)
labels = torch.tensor([0, 1, 0, 1])
optimizer.zero_grad() # 清空梯度
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward() # 反向传播
optimizer.step() # 更新参数
print(criterion(outputs, labels)) # tensor(0.6918, grad_fn=<NllLossBackward0>)
数据处理
数据集
torch.utils.data.Dataset 是一个抽象类,用于表示数据集,用户可以自定义数据集类,通过重写 __getitem__ 和 __len__ 方法来实现对数据的访问和获取数据集的大小
数据加载器
torch.utils.data.DataLoader 是一个可迭代对象,它封装了数据集,并提供了批量加载、打乱数据、多线程数据加载等功能,方便在训练过程中高效地获取数据
## 数据处理
from torch.utils.data import Dataset, DataLoader
# 自定义数据集
class MyDataset(Dataset):
def __init__(self, data, labels):
self.data = data
self.labels = labels
def __getitem__(self, index):
return self.data[index], self.labels[index]
def __len__(self):
return len(self.data)
data = torch.randn(100, 10)
labels = torch.randint(0, 2, (100,))
dataset = MyDataset(data, labels)
dataloader = DataLoader(dataset, batch_size=10, shuffle=True)
# 使用数据加载器
for inputs, labels in dataloader:
print(inputs.shape, labels.shape)
# torch.Size([10, 10]) torch.Size([10])
# torch.Size([10, 10]) torch.Size([10])
# torch.Size([10, 10]) torch.Size([10])
# torch.Size([10, 10]) torch.Size([10])
# torch.Size([10, 10]) torch.Size([10])
# torch.Size([10, 10]) torch.Size([10])
# torch.Size([10, 10]) torch.Size([10])
# torch.Size([10, 10]) torch.Size([10])
# torch.Size([10, 10]) torch.Size([10])
# torch.Size([10, 10]) torch.Size([10])
模型保存与加载
保存模型
torch.save(model.state_dict(), 'model.pth')
只保存模型的参数,这种方式保存的文件较小,且在加载模型时需要先定义相同的模型结构
torch.save(model, 'model.pth')
保存整个模型,包括模型的结构和参数,这种方式保存的文件较大,但加载时不需要定义模型结构
## 数据保存与加载
# 保存模型
torch.save(model.state_dict(), 'model.pth') # 保存参数
torch.save(model, 'model.pth') # 保存整个模型
加载模型
对于只保存参数的方式,需要先定义相同的模型结构,然后使用 model.load_state_dict(torch.load('model.pth')) 加载模型参数
对于保存整个模型的方式,可以直接使用 torch.load('model.pth') 加载模型,然后将其分配给一个变量即可使用
# 加载模型
model = MyModel()
model.load_state_dict(torch.load('model.pth')) # 加载参数
model = torch.load('model.pth') # 加载整个模型
分布式训练
多GPU训练
PyTorch提供了 torch.nn.DataParallel 和 torch.nn.parallel.DistributedDataParallel 等模块,用于在多GPU环境下进行模型训练,可以显著提高训练速度
分布式数据加载
在分布式训练中, torch.utils.data.distributed.DistributedSampler 可以根据进程数和进程编号对数据集进行分片,确保每个进程加载的数据是不同的,从而实现数据的分布式加载
## 分布式训练
import torch.distributed as dist
import torch.nn.parallel
# 初始化分布式环境
dist.init_process_group(backend='nccl', init_method='env://')
# 多GPU训练
model = MyModel()
model = torch.nn.DataParallel(model)
# model = torch.nn.parallel.DistributedDataParallel(model)
# 分布式数据加载
sampler = torch.utils.data.distributed.DistributedSampler(dataset)
dataloader = DataLoader(dataset, batch_size=10, sampler=sampler)
其他功能
设备管理
可以通过 torch.device 对象来指定张量和模型所在的设备,如 torch.device('cuda:0') 表示使用第一块GPU, torch.device('cpu') 表示使用CPU
随机数种子设置
使用 torch.manual_seed(seed) 可以设置随机数种子,确保每次运行代码时生成的随机数是相同的,这对于实验的可重复性非常重要
模型推理
在模型推理阶段,可以使用 model.eval() 将模型切换到评估模式,这会关闭 Dropout 和 BatchNorm 等层的训练特性,以确保模型在推理时的行为是正确的
## 其他功能
# 设备管理
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
tensor = torch.tensor([1, 2, 3], device=device)
# 随机数种子设置
torch.manual_seed(42)
random_tensor = torch.randn((3, 3))
# 模型推理
model.eval() # 切换到评估模式
with torch.no_grad(): # 关闭梯度计算
outputs = model(inputs)