[Japanese] How to Initialize Weights in PyTorch
PyTorchでの重みの初期化方法に関する簡単なチュートリアル。コードとインタラクティブな可視化を含む。
Created on August 1|Last edited on August 1
Comment
目次
説明内容
この記事では、PyTorchモデルのさまざまな層の重みをどのように初期化するかについて見ていきます。
Tensorflowとは異なり、PyTorchはさまざまなレイヤーで重みを初期化するための簡単なインターフェースを提供していません(ただし、torch.nn.init は物体) そのため、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)
PyTorchの重み初期化実験
以下のWeights & Biasesのチャートは、重み初期化をよりよく示すために提供されたColabから描かれています。再度、こちらで確認できます。
ここでは、正規分布のさまざまな標準偏差が、性能の観点からどのように異なるかを確認できます。
Run set
42
標準偏差の値が大きいと良い結果に結びつかず、局所的な最小値に達する可能性が高いです。一方、値が小さいとパフォーマンスが大幅に向上します。
要約
この記事では、PyTorchのディープラーニングモデルの重みを初期化する方法と、Weights & Biasesを使用してメトリクスを監視することで貴重な洞察が得られる方法について説明しました。
W&Bの機能一覧を見るにはこちらをご覧ください。5分間ガイド数学や「ゼロからの」コード実装をカバーするレポートがもっと必要な場合は、以下のコメント欄または私たちの上でお知らせください。フォーラム ✨!
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