Pytorch Tutorial-Training Models
这是我学习Pytorch时记录的一些笔记 ,希望能对你有所帮助😊
Introduction
In past sections, we’ve discussed and demonstrated:
- Building models with the
neural network layers
and functions of thetorch.nn module
- The mechanics of
automated gradient computation
, which is central to gradient-based model training - Using
TensorBoard
to visualize training progress and other activities
In this section, we’ll be adding some new tools to your inventory:
- We’ll get familiar with the
dataset and dataloader
abstractions, and how they ease the process of feeding data to your model during a training loop - We’ll discuss specific
loss functions
and when to use them - We’ll look at
PyTorch optimizers
, which implement algorithms to adjust model weights based on the outcome of a loss function
Finally, we’ll pull all of these together and see a full PyTorch training loop in action.
Dataset and DataLoader
The Dataset
and DataLoader
classes encapsulate the process of pulling your data from storage and exposing it to your training loop in batches.
The Dataset
is responsible for accessing and processing single instances of data.
The DataLoader
pulls instances of data from the Dataset
(either automatically or with a sampler that you define), collects them in batches, and returns them for consumption by your training loop. The DataLoader
works with all kinds of datasets, regardless of the type of data they contain.
For this tutorial, we’ll be using the Fashion-MNIST dataset provided by TorchVision.
1 |
|
As always, let’s visualize the data as a sanity check:
1 |
|
make_grid
是 PyTorch 中用于将多张图像拼接成网格的工具,常用于可视化批次数据或特征图
The Model
The model we’ll use in this example is a variant of LeNet-5
- it should be familiar if you’ve watched the previous videos in this series.
1 |
|
Loss Funtion
For this example, we’ll be using a cross-entropy loss
. For demonstration purposes, we’ll create batches of dummy output and label values, run them through the loss function, and examine the result.
1 |
|
Optimizer
For this example, we’ll be using simple stochastic gradient descent with momentum.
It can be instructive to try some variations on this optimization scheme:
Learning rate
determines the size of the steps the optimizer takes. What does a different learning rate do to the your training results, in terms of accuracy and convergence time?Momentum
nudges the optimizer in the direction of strongest gradient over multiple steps. What does changing this value do to your results?- Try some different optimization algorithms, such as
averaged SGD
,Adagrad
, orAdam
. How do your results differ?
1 |
|
torch.optim.SGD
是 PyTorch 中实现 随机梯度下降(Stochastic Gradient Descent) 的优化器,支持基础的 SGD 和带动量的 SGD(Momentum SGD)。以下是其核心参数、数学原理和使用方法。
1. 核心参数
参数名 | 类型 | 默认值 | 说明 |
---|---|---|---|
params | iterable | - | 待优化的模型参数(通常为 model.parameters() )。 |
lr | float | - | 学习率(必须指定),控制参数更新步长。 |
momentum | float | 0 | 动量因子(0 表示普通 SGD),加速收敛并减少震荡。 |
dampening | float | 0 | 动量阻尼(通常与 momentum 配合使用)。 |
weight_decay | float | 0 | L2 正则化系数(防止过拟合)。 |
nesterov | bool | False | 是否启用 Nesterov 动量(需 momentum > 0 )。 |
2. 数学原理
(1) 普通 SGD(无动量)
参数更新公式:
$$
\theta_{t+1} = \theta_t - \eta \cdot \nabla_\theta J(\theta_t)
$$
- $\theta_t$:第 $t$ 步的参数。
- $\eta$:学习率(
lr
)。 - $\nabla_\theta J(\theta_t)$:损失函数对参数的梯度。
(2) 带动量的 SGD
引入动量项 $v_t$:
$$
\begin{align}v_{t+1} &= \mu \cdot v_t + \nabla_\theta J(\theta_t) \
\theta_{t+1} &= \theta_t - \eta \cdot v_{t+1}\end{align}
$$
- $\mu$:动量系数(
momentum
,通常设为 0.9)。 - 动量通过累积历史梯度方向,加速收敛并抑制震荡。
(3) Nesterov 动量
在计算梯度时先进行“试探性”更新:
$$
v_{t+1} = \mu \cdot v_t + \nabla_\theta J(\theta_t - \eta \mu v_t) \
\theta_{t+1} = \theta_t - \eta \cdot v_{t+1}
$$
- 相比普通动量,Nesterov 动量对梯度方向更敏感,收敛更快。
3. 适用场景
场景 | 推荐配置 | 说明 |
---|---|---|
简单任务 | lr=0.01 , momentum=0 | 数据量小、模型简单时,普通 SGD 足够。 |
深层网络训练 | lr=0.1 , momentum=0.9 | 动量帮助加速收敛,避免陷入局部最优。 |
对抗训练 | lr=0.01 , momentum=0.9 , nesterov=True | Nesterov 动量提升对抗样本生成效果。 |
稀疏数据 | lr=0.001 , weight_decay=1e-4 | L2 正则化防止过拟合。 |
6. 与其他优化器对比
优化器 | 优点 | 缺点 |
---|---|---|
SGD | 理论收敛性好,调参简单。 | 需手动调学习率,可能收敛慢。 |
Adam | 自适应学习率,适合大多数任务。 | 可能在某些任务上泛化性差。 |
RMSprop | 适合非平稳目标(如 RNN)。 | 对超参数敏感。 |
通过合理配置 torch.optim.SGD
,你可以在训练速度和模型性能之间取得平衡。对于复杂任务,建议尝试 Adam
或 SGD + 动量
并对比效果。
The Training Loop
Below, we have a function that performs one training epoch. It enumerates data from the DataLoader, and on each pass of the loop does the following:
- Gets a batch of training data from the DataLoader
- Zeros the optimizer’s gradients
- Performs an inference - that is, gets predictions from the model for an input batch
- Calculates the loss for that set of predictions vs. the labels on the dataset
- Calculates the backward gradients over the learning weights
- Tells the optimizer to perform one learning step - that is, adjust the model’s learning weights based on the observed gradients for this batch, according to the optimization algorithm we chose
- It reports on the loss for every 1000 batches.
- Finally, it reports the average per-batch loss for the last 1000 batches, for comparison with a validation run
1 |
|
Per-Epoch Activity
There are a couple of things we’ll want to do once per epoch:
- Perform validation by checking our relative loss on a set of data that was not used for training, and report this
- Save a copy of the model
Here, we’ll do our reporting in TensorBoard. This will require going to the command line to start TensorBoard, and opening it in another browser tab.
1 |
|
1 |
|
To load a saved version of the model:
1 |
|
Once you’ve loaded the model, it’s ready for whatever you need it for - more training, inference, or analysis.
Note that if your model has constructor parameters that affect model structure, you’ll need to provide them and configure the model identically to the state in which it was saved.
Other Resources
- Docs on the data utilities, including Dataset and DataLoader, at pytorch.org
- A note on the use of pinned memory for GPU training
- Documentation on the datasets available in TorchVision, TorchText, and TorchAudio
- Documentation on the loss functions available in PyTorch
- Documentation on the torch.optim package, which includes optimizers and related tools, such as learning rate scheduling
- A detailed tutorial on saving and loading models
- The Tutorials section of pytorch.org contains tutorials on a broad variety of training tasks, including classification in different domains, generative adversarial networks, reinforcement learning, and more