如何在PyTorch中对权重进行初始化
本文是关于如何在PyTorch中使用代码和交互式可视化方式对权重进行初始化的简短教程。
Created on August 15|Last edited on August 17
Comment
目录
我们将介绍什么
在本文中,我们将介绍如何在PyTorch模型中对多层权重进行初始化。
与Tensorflow不同,PyTorch并没有提供简单明了的界面来对多层权重进行初始化(虽然有 torch.nn.init 这个东西),所以在您想要按照众所周知的技巧(比如:Xavier 或 He Initialization )来对权重进行初始化时,情况就会有些复杂。
下面我们将介绍如何对权重进行初始化,不过如果您想参考可执行的 Colab 例子,则可前往:
💡
借助类函数在 PyTorch 中将权重初始化为 0
对权重进行初始化的最流行方式之一,是使用可在自定义 PyTorch 模块 __init__ 函数末尾进行调用的类函数。
import torch.nn as nnclass Model(nn.Module):# . . .def __init__(self):# .self.apply(self._init_weights)def _init_weights(self, module):if isinstance(module, nn.Linear):module.weight.data.normal_(mean=0.0, std=1.0)if module.bias is not None:module.bias.data.zero_()
这里的代码片段从均值为 0、标准差为 1 的正态分布中初始化了所有权重,并将所有的偏差初始化为 0。如果想将其扩展至 nn.LayerNorm and nn.Embedding 等层,其中所涉及的工作也会非常轻松。
def _init_weights(self, module):if isinstance(module, nn.Embedding):module.weight.data.normal_(mean=0.0, std=1.0)if module.padding_idx is not None:module.weight.data[module.padding_idx].zero_()elif isinstance(module, nn.LayerNorm):module.bias.data.zero_()module.weight.data.fill_(1.0)
PyTorch权重初始化试验
下方Weights & Biases图表的数据来源于提供的 Colab,很好地展示整个权重初始化过程。同样,您可在下方查看更多信息:
这里我们可以看到正态分布的各个标准差在性能方面的区别。
显然,大的标准差值不会带来更好的结果,而是很可能导致局部最小值。较小的标准差值则有助于实现更好的结果。
总结
在本文中,我们讲解了如何为PyTorch深度学习模型初始化权重,以及如何使用Weights & Biases来对指标进行监控并从中获得有价值的洞察信息。
试试Weights & Biases
Weights & Biases能够帮助您对自己的机器学习实验进行跟踪。您可尝试使用我们的工具来记录各项指标(无论是超参数还是运行输出指标),还可对结果进行可视化与对比,便于您快速与同事分享发现。
说明:
- 点击下方的绿色“运行”按钮(首次点击运行时,Replit将需要30-45秒的时间来分配机器)
- 按照终端窗口中的提示进行操作(右下方的窗格)
- 您可对终端窗口(右下)的大小进行调整
推荐阅读
How To Use GPU with PyTorch
A short tutorial on using GPUs for your deep learning models with PyTorch, from checking availability to visualizing usable.
A Gentle Introduction To Weight Initialization for Neural Networks
An explainer and comprehensive overview of various strategies for neural network weight initialization
PyTorch Dropout for regularization - tutorial
Learn how to regularize your PyTorch model with Dropout, complete with a code tutorial and interactive visualizations
How to save and load models in PyTorch
This article is a machine learning tutorial on how to save and load your models in PyTorch using Weights & Biases for version control.
Image Classification Using PyTorch Lightning and Weights & Biases
This article provides a practical introduction on how to use PyTorch Lightning to improve the readability and reproducibility of your PyTorch code.
How to Compare Keras Optimizers in Tensorflow for Deep Learning
A short tutorial outlining how to compare Keras optimizers for your deep learning pipelines in Tensorflow, with a Colab to help you follow along.
Add a comment
Iterate on AI agents and models faster. Try Weights & Biases today.