PyTorchでの重みの初期化方法
PyTorchでコードとインタラクティブな可視化を用いて重みを初期化する方法に関する短いチュートリアル。
Created on August 1|Last edited on August 1
Comment
目次
私たちが取り上げる内容
この記事では、PyTorchモデルのさまざまな層の重みを初期化する方法について見ていきます。
Tensorflowとは異なり、PyTorchはさまざまなレイヤーでの重みの初期化を簡単に行うインターフェースを提供していません(ただしトーチ・エヌエヌ・イニット ですあるもの)、そのためXavierやHeの初期化といった有名な手法に従って重みを初期化したい場合、難しくなります。
以下で重みの初期化方法を見ていきますが、実行可能なColabで一緒に進めたい場合は、こちらでできます:
💡
PyTorchでクラス関数を使用して重みをゼロに初期化する
最も一般的な重みの初期化方法の一つは、クラス関数を使用し、それを最後に呼び出すことです。__init__カスタムPyTorchモデル内の関数。
import torch.nn as nn class 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の正規分布からすべての重みを初期化し、すべてのバイアスをゼロに初期化します。他の層にこれを拡張するのは非常に簡単です。nn.LayerNormおよび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)
パイトーチ重み初期化実験
以下のWeights & Biasesのチャートは、重みの初期化をより良く説明するために提供されたColabから描かれています。再度、こちらで見つけることができます:
ここでは、正規分布のさまざまな標準偏差がパフォーマンスの面でどのように異なるかを見ることができます。
Run set
42
明らかに標準偏差の大きい値は良い結果をもたらさず、ほとんどの場合局所的な最小値に至ります。一方で、値が小さいほどパフォーマンスが向上します。
概要
この記事では、PyTorchのディープラーニングモデルの重みを初期化する方法と、Weights & Biasesを使用してメトリクスを監視することが価値のある洞察につながる方法を見ました。
W&Bの全機能を見るには、こちらをご覧ください。short 5 minutes guide。数学や「ゼロからの」コード実装をカバーするレポートをもっと欲しい場合は、以下のコメント欄や我々の上でお知らせください。forum ✨!
Weights & Biasesを試してみてください。
Weights & Biasesは、機械学習実験を追跡するのに役立ちます。私たちのツールを試して、ハイパーパラメーターをログし、runから出力されたメトリクスを記録し、結果を視覚化して比較し、学びを迅速に同僚と共有しましょう。
指示:
- 下の緑色の「実行」ボタンをクリックしてください。初めて実行をクリックした時、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