PyTorch torch.nn リファレンスマニュアル

PyTorch のtorch.nnモジュールはニューラルネットワークの構築とトレーニングの中核となるモジュールであり、ニューラルネットワークを定義・操作するための豊富なクラスと関数を提供します。

以下はtorch.nnモジュールの主要な構成要素とその機能:

1、nn.Module クラス:

  • nn.Moduleすべてのカスタムニューラルネットワークモデルの基底クラスです。ユーザーは通常、このクラスから独自のモデルクラスを派生させ、その中でネットワーク層の構造と順伝播関数(forward pass)を定義します。

2、定義済み層(Modules):

  • さまざまな種類の層コンポーネントが含まれます。たとえば、畳み込み層(nn.Conv1d, nn.Conv2d, nn.Conv3d)、全結合層(nn.Linear)、活性化関数(nn.ReLU, nn.Sigmoid, nn.Tanh)など。

3、コンテナクラス:

  • nn.Sequential:複数の層を順番に組み合わせて、シンプルな線形積層ネットワークを形成することができます。
  • nn.ModuleListとnn.ModuleDict:サブモジュールを動的に保存およびアクセスでき、可変長または名前付きのモジュールコレクションをサポートします。

4、損失関数(Loss Functions):

  • torch.nnモデルの予測と実際のラベルとの間の差異を測定するための一連の損失関数が含まれています。例:平均二乗誤差損失(nn.MSELoss)、交差エントロピー損失(nn.CrossEntropyLoss)など。

5、関数型インターフェース(Functional Interface):

  • nn.functional(通常はFと略記されます)、テンソルに直接作用する多くの関数が含まれており、層オブジェクトと同じ機能を実装していますが、パラメータの保存や更新の機能はありません。たとえば、F.relu()を使用して直接 ReLU 操作を行うことができ、またはF.conv2d()を使用して畳み込み操作を行うことができます。

6、初期化メソッド:

  • torch.nn.initよく使われる重み初期化戦略を提供します。たとえば、Xavier 初期化(nn.init.xavier_uniform_())や Kaiming 初期化(nn.init.kaiming_uniform_())などは、ニューラルネットワークのトレーニングを成功させるために不可欠です。

7、Transformer 層:

  • PyTorch は完全な Transformer アーキテクチャコンポーネントを提供します。含まれるもの:nn.Transformer, nn.TransformerEncoder, nn.TransformerDecoderおよびアテンション機構nn.MultiheadAttentionなど。

8、正規化層:

  • バッチ正規化(BatchNorm)、層正規化(LayerNorm)、グループ正規化(GroupNorm)、インスタンス正規化(InstanceNorm)、および RMSNorm などが含まれます。

PyTorch torch.nn モジュールリファレンスマニュアル

ニューラルネットワークコンテナ

クラス/関数 説明
torch.nn.Module すべてのニューラルネットワークモジュールの基底クラス。
torch.nn.Sequential(*args) 複数のモジュールを順番に組み合わせます。
torch.nn.ModuleList(modules) サブモジュールをリストに保存します。
torch.nn.ModuleDict(modules) サブモジュールを辞書に保存します。
torch.nn.ParameterList(parameters) パラメータをリストに保存します。
torch.nn.ParameterDict(parameters) パラメータを辞書に保存します。
torch.nn.Parameter(data) 学習可能なパラメータテンソルを作成します。
torch.nn.Buffer(data) 永続化されたバッファ(非学習パラメータ)を作成します。
torch.nn.Identity(*args, **kwargs) 恒等変換層。入力をそのまま出力します。

グローバルフック(Global Hooks)

関数 説明
register_module_forward_pre_hook(hook) フォワード事前フックを登録します。
register_module_forward_hook(hook) フォワードフックを登録します。
register_module_backward_hook(hook) バックワードフックを登録します。
register_module_full_backward_pre_hook(hook) 完全なバックワード事前フックを登録します。
register_module_full_backward_hook(hook) 完全なバックワードフックを登録します。

線形層

クラス/関数 説明
torch.nn.Linear(in_features, out_features, bias) 全結合層(線形変換)。
torch.nn.Bilinear(in1_features, in2_features, out_features, bias) 双線形層。
torch.nn.LazyLinear(out_features, bias) 遅延初期化された線形層。最初のフォワード伝播時に入力次元を自動的に推論します。

畳み込み層

クラス/関数 説明
torch.nn.Conv1d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias, padding_mode) 1次元畳み込み層。テキストやオーディオによく使用されます。
torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias, padding_mode) 2次元畳み込み層。画像によく使用されます。
torch.nn.Conv3d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias, padding_mode) 3次元畳み込み層。ビデオやボリュームデータによく使用されます。
torch.nn.ConvTranspose1d(in_channels, out_channels, kernel_size, stride, padding, output_padding, groups, bias, dilation, padding_mode) 1次元転置畳み込み(逆畳み込み)。アップサンプリングに使用されます。
torch.nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride, padding, output_padding, groups, bias, dilation, padding_mode) 2次元転置畳み込み(逆畳み込み)。アップサンプリングに使用されます。
torch.nn.ConvTranspose3d(in_channels, out_channels, kernel_size, stride, padding, output_padding, groups, bias, dilation, padding_mode) 3次元転置畳み込み(逆畳み込み)。アップサンプリングに使用されます。
torch.nn.Unfold(kernel_size, dilation, padding, stride) 入力テンソルをスライディングウィンドウのブロックに展開します。
torch.nn.Fold(output_size, kernel_size, dilation, padding, stride) 展開されたブロックをテンソルに再構成します。

プーリング層

クラス/関数 説明
torch.nn.MaxPool1d(kernel_size, stride, padding, dilation, return_indices) 1次元最大プーリング層。
torch.nn.MaxPool2d(kernel_size, stride, padding, dilation, return_indices, ceil_mode) 2次元最大プーリング層。
torch.nn.MaxPool3d(kernel_size, stride, padding, dilation, return_indices, ceil_mode) 3次元最大プーリング層。
torch.nn.MaxUnpool1d(kernel_size, stride, padding) 1次元最大アンプーリング層。
torch.nn.MaxUnpool2d(kernel_size, stride, padding) 2次元最大アンプーリング層。
torch.nn.MaxUnpool3d(kernel_size, stride, padding) 3次元最大アンプーリング層。
torch.nn.AvgPool1d(kernel_size, stride, padding) 1次元平均プーリング層。
torch.nn.AvgPool2d(kernel_size, stride, padding, ceil_mode, count_include_pad) 2次元平均プーリング層。
torch.nn.AvgPool3d(kernel_size, stride, padding, ceil_mode, count_include_pad) 3次元平均プーリング層。
torch.nn.AdaptiveMaxPool1d(output_size, return_indices) 1次元適応的最大プーリング。出力サイズは固定。
torch.nn.AdaptiveMaxPool2d(output_size, return_indices) 2次元適応的最大プーリング。出力サイズは固定。
torch.nn.AdaptiveMaxPool3d(output_size, return_indices) 3次元適応的最大プーリング。出力サイズは固定。
torch.nn.AdaptiveAvgPool1d(output_size) 1次元適応的平均プーリング。出力サイズは固定。
torch.nn.AdaptiveAvgPool2d(output_size) 2次元適応的平均プーリング。出力サイズは固定。
torch.nn.AdaptiveAvgPool3d(output_size) 3次元適応的平均プーリング。出力サイズは固定。
torch.nn.LPPool1d(norm_type, kernel_size, stride, padding) 1次元 Lp プーリング層。
torch.nn.LPPool2d(norm_type, kernel_size, stride, padding) 2次元 Lp プーリング層。
torch.nn.FractionalMaxPool2d(kernel_size, output_size, output_ratio, return_indices) 2次元分数最大プーリング。ランダムなストライドを使用。
torch.nn.FractionalMaxPool3d(kernel_size, output_size, output_ratio, return_indices) 3次元分数最大プーリング。ランダムなストライドを使用。

パディング層(Padding Layers)

クラス/関数 説明
torch.nn.ReflectionPad1d(padding) 1次元反射パディング。境界に沿って反射コピー。
torch.nn.ReflectionPad2d(padding) 2次元反射パディング。境界に沿って反射コピー。
torch.nn.ReflectionPad3d(padding) 3次元反射パディング。境界に沿って反射コピー。
torch.nn.ReplicationPad1d(padding) 1次元複製パディング。境界に沿って端の値をコピー。
torch.nn.ReplicationPad2d(padding) 2次元複製パディング。境界に沿って端の値をコピー。
torch.nn.ReplicationPad3d(padding) 3次元複製パディング。境界に沿って端の値をコピー。
torch.nn.ZeroPad1d(padding) 1次元ゼロパディング。
torch.nn.ZeroPad2d(padding) 2次元ゼロパディング。
torch.nn.ZeroPad3d(padding) 3次元ゼロパディング。
torch.nn.ConstantPad1d(padding, value) 1次元定数パディング。指定された値で埋めます。
torch.nn.ConstantPad2d(padding, value) 2次元定数パディング。指定された値で埋めます。
torch.nn.ConstantPad3d(padding, value) 3次元定数パディング。指定された値で埋めます。
torch.nn.CircularPad1d(padding) 1次元循環パディング。
torch.nn.CircularPad2d(padding) 2次元循環パディング。
torch.nn.CircularPad3d(padding) 3次元循環パディング。

活性化関数(非線形活性化 - 重み付き和タイプ)

クラス/関数 説明
torch.nn.ReLU(inplace) ReLU 活性化関数、f(x) = max(0, x)。
torch.nn.ReLU6(inplace) ReLU6 活性化関数、f(x) = min(max(0, x), 6)。
torch.nn.Sigmoid() Sigmoid 活性化関数、f(x) = 1 / (1 + exp(-x))。
torch.nn.Tanh() Tanh 活性化関数、f(x) = (exp(x) - exp(-x)) / (exp(x) + exp(-x))。
torch.nn.LeakyReLU(negative_slope, inplace) LeakyReLU。負の値に小さな勾配を許容します。
torch.nn.PReLU(num_parameters, init) パラメータ化 ReLU。学習可能な負の傾きパラメータを持ちます。
torch.nn.ELU(alpha, inplace) 指数線形ユニット。負の値には指数関数を使用します。
torch.nn.CELU(alpha, inplace) 連続微分可能な指数線形ユニット。
torch.nn.SELU(inplace) 自己正規化指数線形ユニット。
torch.nn.GELU() ガウス誤差線形ユニット。Transformer でよく使用されます。
torch.nn.SiLU(inplace) Sigmoid 線形ユニット(Swish)、f(x) = x * sigmoid(x)。
torch.nn.Mish(inplace) Mish 活性化関数、f(x) = x * tanh(softplus(x))。
torch.nn.Hardtanh(min_value, max_value, inplace) ハード双曲線正接。出力範囲を制限します。
torch.nn.Hardswish(inplace) Hard Swish。ReLU6 の滑らかなバージョン。
torch.nn.Hardsigmoid(inplace) Hard Sigmoid。区分線形近似。
torch.nn.RReLU(lower, upper, inplace) ランダム LeakyReLU。トレーニング時に負の傾きをランダムに選択します。
torch.nn.Softplus(beta, threshold) Softplus。ReLU の滑らかな近似。
torch.nn.Softshrink(lambda) Softshrink 活性化関数。
torch.nn.Hardshrink(lambda) Hardshrink 活性化関数。
torch.nn.Softsign() Softsign 活性化関数、f(x) = x / (1 + |x|)。
torch.nn.Tanhshrink() Tanhshrink,f(x) = x - tanh(x)。
torch.nn.LogSigmoid() Log Sigmoid,f(x) = log(sigmoid(x))。
torch.nn.Threshold(threshold, value, inplace) しきい値活性化関数。
torch.nn.GLU(dim) ゲート付き線形ユニット。入力を指定された次元に沿って2つの部分に分割し、要素ごとに乗算します。

活性化関数(非線形活性化 - その他)

クラス/関数 説明
torch.nn.Softmax(dim) Softmax 活性化関数。数値を確率分布に変換します。
torch.nn.Softmax2d() 空間次元に対する Softmax。画像に使用されます。
torch.nn.LogSoftmax(dim) Log Softmax、数値的に安定なバージョンの Softmax。
torch.nn.Softmin(dim) Softmin、Softmax の逆。
torch.nn.AdaptiveLogSoftmaxWithLoss(in_features, n_classes, cutoffs, div_value, head_bias) 適応的Log Softmax、大語彙分類用。

正規化層

クラス/関数 説明
torch.nn.BatchNorm1d(num_features, eps, momentum, affine, track_running_stats) 1次元バッチ正規化層。ミニバッチデータを正規化する。
torch.nn.BatchNorm2d(num_features, eps, momentum, affine, track_running_stats) 2次元バッチ正規化層。畳み込みネットワークでよく使われる。
torch.nn.BatchNorm3d(num_features, eps, momentum, affine, track_running_stats) 3次元バッチ正規化層。動画などの3次元データ用。
torch.nn.LazyBatchNorm1d() 遅延初期化の1次元バッチ正規化。
torch.nn.LazyBatchNorm2d() 遅延初期化の2次元バッチ正規化。
torch.nn.LazyBatchNorm3d() 遅延初期化の3次元バッチ正規化。
torch.nn.LayerNorm(normalized_shape, eps, elementwise_affine) レイヤー正規化。Transformer でよく使われる。
torch.nn.GroupNorm(num_groups, num_channels, eps, affine) グループ正規化。チャンネルをグループ化して正規化する。
torch.nn.InstanceNorm1d(num_features, eps, momentum, affine, track_running_stats) 1次元インスタンス正規化。スタイル変換用。
torch.nn.InstanceNorm2d(num_features, eps, momentum, affine, track_running_stats) 2次元インスタンス正規化。スタイル変換用。
torch.nn.InstanceNorm3d(num_features, eps, momentum, affine, track_running_stats) 3次元インスタンス正規化。スタイル変換用。
torch.nn.SyncBatchNorm(num_features, eps, momentum, affine, track_running_stats, process_group) 同期バッチ正規化。マルチGPU分散訓練用。
torch.nn.LocalResponseNorm(k, alpha, beta, size) 局所応答正規化。畳み込みニューラルネットワークで横方向抑制に使われる。
torch.nn.RMSNorm(normalized_shape, eps, elementwise_affine) RMS正規化。Transformer でよく使われる。

リカレントニューラルネットワーク層

クラス/関数 説明
torch.nn.RNN(input_size, hidden_size, num_layers, nonlinearity, bias, batch_first, dropout, bidirectional) シンプルなRNN層。
torch.nn.LSTM(input_size, hidden_size, num_layers, bias, batch_first, dropout, bidirectional, proj_size) LSTM(長短期記憶)層。
torch.nn.GRU(input_size, hidden_size, num_layers, bias, batch_first, dropout, bidirectional, proj_size) GRU(ゲート付きリカレントユニット)層。
torch.nn.RNNCell(input_size, hidden_size, bias, nonlinearity) RNNセル(単層)。
torch.nn.LSTMCell(input_size, hidden_size, bias) LSTMセル(単層)。
torch.nn.GRUCell(input_size, hidden_size, bias) GRUセル(単層)。

Transformer 層

クラス/関数 説明
torch.nn.Transformer(d_model, nhead, num_encoder_layers, num_decoder_layers, dim_feedforward, dropout, activation, custom_encoder, custom_decoder, layer_norm_eps, normalize_before, need_src_mask, need_tgt_mask, need_memory_mask, batch_first, norm_first, bias) 完全なTransformerモデル。
torch.nn.TransformerEncoder(encoder_layer, num_layers, norm) Transformerエンコーダー。
torch.nn.TransformerDecoder(decoder_layer, num_layers, norm) Transformerデコーダー。
torch.nn.TransformerEncoderLayer(d_model, nhead, dim_feedforward, dropout, activation, layer_norm_eps, batch_first, norm_first, bias) Transformerエンコーダー層。
torch.nn.TransformerDecoderLayer(d_model, nhead, dim_feedforward, dropout, activation, layer_norm_eps, batch_first, norm_first, bias) Transformerデコーダー層。
torch.nn.MultiheadAttention(embed_dim, num_heads, dropout, bias, add_bias_kv, add_zero_attn, kdim, vdim, batch_first) マルチヘッドアテンション機構。

アテンション機構(Attention)

関数 説明
torch.nn.functional.scaled_dot_product_attention(query, key, value, attn_mask, dropout_p, is_causal) スケールド・ドット積アテンション。PyTorch最適化アテンション実装。
torch.nn.attention.sdpa_kernel(backends) SDP(スケールド・ドット積アテンション)バックエンドを設定する。

埋め込み層(スパース層)

クラス/関数 説明
torch.nn.Embedding(num_embeddings, embedding_dim, padding_idx, max_norm, norm_type, scale_grad_by_freq, sparse) 埋め込み層。離散インデックスを密ベクトルにマッピングする。
torch.nn.EmbeddingBag(num_embeddings, embedding_dim, max_norm, norm_type, scale_grad_by_freq, mode, sparse, per_sample_weights, include_last_offset, padding_idx) EmbeddingBag。複数の埋め込みを集約する。

Dropout 層

クラス/関数 説明
torch.nn.Dropout(p, inplace) Dropout層。入力要素をランダムにゼロにする。
torch.nn.Dropout1d(p, inplace) 1次元Dropout。1次元入力用。
torch.nn.Dropout2d(p, inplace) 2次元Dropout。2次元特徴マップ用。
torch.nn.Dropout3d(p, inplace) 3次元Dropout。3次元特徴ボリューム用。
torch.nn.AlphaDropout(p, inplace) Alpha Dropout。自己正規化特性を維持する。
torch.nn.FeatureAlphaDropout(p, inplace) 特徴Alpha Dropout。

ビジョン層(Vision Layers)

クラス/関数 説明
torch.nn.PixelShuffle(upscale_factor) ピクセルシャッフル。チャンネル次元を空間次元に変換する(アップサンプリング)。
torch.nn.PixelUnshuffle(downscale_factor) ピクセルシャッフルの逆操作。空間次元をチャンネル次元に変換する(ダウンサンプリング)。
torch.nn.Upsample(size, scale_factor, mode, align_corners, recompute_scale_factor) アップサンプリング層。
torch.nn.UpsamplingNearest2d(size, scale_factor) 2次元最近傍アップサンプリング。
torch.nn.UpsamplingBilinear2d(size, scale_factor, align_corners) 2次元バイリニアアップサンプリング。
torch.nn.ChannelShuffle(groups) チャンネルシャッフル。ChannelShuffle ネットワーク用。

損失関数

クラス/関数 説明
torch.nn.MSELoss(size_average, reduce, reduction) 平均二乗誤差損失(Mean Squared Error)。
torch.nn.L1Loss(size_average, reduce, reduction) L1損失(平均絶対誤差)。
torch.nn.CrossEntropyLoss(weight, size_average, ignore_index, reduce, reduction, label_smoothing) 交差エントロピー損失。多クラス分類タスク用。
torch.nn.NLLLoss(weight, size_average, ignore_index, reduce, reduction) 負の対数尤度損失。
torch.nn.BCELoss(weight, size_average, reduce, reduction) バイナリ交差エントロピー損失(2値分類)。
torch.nn.BCEWithLogitsLoss(weight, pos_weight, size_average, reduce, reduction, label_smoothing) Sigmoid付きバイナリ交差エントロピー損失。数値的に安定。
torch.nn.KLDivLoss(size_average, reduce, reduction, log_target) KLダイバージェンス損失。分布マッチング用。
torch.nn.HuberLoss(delta, size_average, reduce, reduction) Huber損失。L1とL2の組み合わせで、外れ値に対してより頑健。
torch.nn.SmoothL1Loss(beta, size_average, reduce, reduction) スムーズL1損失(Huber損失の変種)。
torch.nn.CTCLoss(blank, reduction, zero_infinity) CTC損失。音声認識などのシーケンスタスク用。
torch.nn.PoissonNLLLoss(log_input, full, size_average, reduce, reduction) ポアソン負の対数尤度損失。
torch.nn.GaussianNLLLoss(full, size_average, reduce, reduction) ガウス負の対数尤度損失。
torch.nn.MarginRankingLoss(margin, size_average, reduce, reduction) マージンランキング損失。ランキング学習用。
torch.nn.HingeEmbeddingLoss(margin, size_average, reduce, reduction) ヒンジ埋め込み損失。メトリック学習用。
torch.nn.MultiLabelMarginLoss(size_average, reduce, reduction) マルチラベルマージン損失。
torch.nn.SoftMarginLoss(size_average, reduce, reduction) ソフトマージン損失。
torch.nn.MultiLabelSoftMarginLoss(weight, size_average, reduce, reduction) マルチラベルソフトマージン損失。
torch.nn.CosineEmbeddingLoss(margin, size_average, reduce, reduction) コサイン埋め込み損失。メトリック学習用。
torch.nn.MultiMarginLoss(p, margin, weight, size_average, reduce, reduction) 多クラスマージン損失。
torch.nn.TripletMarginLoss(margin, p, eps, swap, size_average, reduce, reduction) トリプレット損失。メトリック学習と対比学習用。
torch.nn.TripletMarginWithDistanceLoss(distance_function, margin, swap, size_average, reduce, reduction) 距離関数付きトリプレット損失。

距離関数

クラス/関数 説明
torch.nn.PairwiseDistance(p, eps, keepdim) ペアワイズ距離計算。
torch.nn.CosineSimilarity(dim, eps) コサイン類似度計算。

並列層(DataParallel)

クラス/関数 説明
torch.nn.DataParallel(module, device_ids, output_device, dim) データ並列。複数のGPU上でモデルを並列実行する。
torch.nn.parallel.DistributedDataParallel(module, device_ids, broadcast_buffers, bucket_cap_mb, find_unused_parameters, gradient_as_bucket_view, static_graph) 分散データ並列。マルチノード分散訓練用。

ユーティリティ関数(nn.functional)

関数 説明
torch.nn.functional.relu(input, inplace) ReLU活性化関数を適用する。
torch.nn.functional.sigmoid(input) Sigmoid活性化関数を適用する。
torch.nn.functional.tanh(input) Tanh活性化関数を適用する。
torch.nn.functional.softmax(input, dim, dtype) Softmax活性化関数を適用する。
torch.nn.functional.log_softmax(input, dim, dtype) Log Softmax活性化関数を適用する。
torch.nn.functional.gelu(input) GELU活性化関数を適用する。
torch.nn.functional.silu(input) SiLU(Swish)活性化関数を適用する。
torch.nn.functional.mish(input) Mish活性化関数を適用する。
torch.nn.functional.hardswish(input) Hardswish活性化関数を適用する。
torch.nn.functional.leaky_relu(input, negative_slope, inplace) LeakyReLU活性化関数を適用する。
torch.nn.functional.elu(input, alpha, inplace) ELU活性化関数を適用する。
torch.nn.functional.dropout(input, p, training, inplace) Dropoutを適用する。
torch.nn.functional.conv1d(input, weight, bias, stride, padding, dilation, groups) 1次元畳み込み操作。
torch.nn.functional.conv2d(input, weight, bias, stride, padding, dilation, groups) 2次元畳み込み操作。
torch.nn.functional.conv3d(input, weight, bias, stride, padding, dilation, groups) 3次元畳み込み操作。
torch.nn.functional.max_pool1d(input, kernel_size, stride, padding, dilation, return_indices) 1次元最大プーリング。
torch.nn.functional.max_pool2d(input, kernel_size, stride, padding, dilation, return_indices, ceil_mode) 2次元最大プーリング。
torch.nn.functional.avg_pool1d(input, kernel_size, stride, padding, ceil_mode, count_include_pad) 1次元平均プーリング。
torch.nn.functional.avg_pool2d(input, kernel_size, stride, padding, ceil_mode, count_include_pad) 2次元平均プーリング。
torch.nn.functional.linear(input, weight, bias) 線形変換(行列乗算)。
torch.nn.functional.cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction, label_smoothing) 交差エントロピー損失を計算する。
torch.nn.functional.mse_loss(input, target, size_average, reduce, reduction) 平均二乗誤差損失を計算する。
torch.nn.functional.l1_loss(input, target, size_average, reduce, reduction) L1損失を計算する。
torch.nn.functional.binary_cross_entropy(input, target, weight, size_average, reduce, reduction) バイナリ交差エントロピー損失を計算する。
torch.nn.functional.nll_loss(input, target, weight, size_average, ignore_index, reduce, reduction) 負の対数尤度損失を計算する。
torch.nn.functional.huber_loss(input, target, delta, size_average, reduce, reduction) Huber損失を計算する。
torch.nn.functional.batch_norm(input, running_mean, running_var, weight, bias, training, momentum, eps, track_running_stats) バッチ正規化操作。
torch.nn.functional.layer_norm(input, normalized_shape, weight, bias, eps) レイヤー正規化操作。
torch.nn.functional.group_norm(input, num_groups, weight, bias, eps) グループ正規化操作。
torch.nn.functional.interpolate(input, size, scale_factor, mode, align_corners, recompute_scale_factor) 補間(アップ/ダウンサンプリング)。
torch.nn.functional.grid_sample(input, grid, mode, padding_mode, align_corners) グリッドサンプリング。画像レジストレーションと空間変換ネットワーク用。
torch.nn.functional.affine_grid(theta, size, align_corners) アフィングリッド生成。空間変換ネットワーク用。
torch.nn.functional.pixel_shuffle(input, upscale_factor) ピクセルシャッフル。
torch.nn.functional.pixel_unshuffle(input, downscale_factor) ピクセルシャッフルの逆操作。
torch.nn.functional.pad(input, pad, mode, value) パディング操作。
torch.nn.functional.one_hot(tensor, num_classes) 整数をワンホットエンコーディングに変換する。
torch.nn.functional.embedding(input, weight, padding_idx, max_norm, norm_type, scale_grad_by_freq, sparse) 埋め込み操作。
torch.nn.functional.cosine_similarity(x1, x2, dim, eps) コサイン類似度計算。
torch.nn.functional.pairwise_distance(x1, x2, p, eps, keepdim) ペアワイズ距離計算。

ユーティリティ関数(nn.utils)

関数 説明
torch.nn.utils.clip_grad_norm_(parameters, max_norm, norm_type, error_if_nonfinite) 勾配ノルムをクリップする(インプレース操作)。
torch.nn.utils.clip_grad_norm(parameters, max_norm, norm_type) 勾配ノルムをクリップする(非インプレース)。
torch.nn.utils.clip_grad_value_(parameters, clip_value) 勾配値を範囲内にクリップする。
torch.nn.utils.get_total_norm(parameters, norm_type) 全勾配ノルムを計算する。
torch.nn.utils.weight_norm(module, name, dim) モジュールパラメータにウェイト正規化を適用する。
torch.nn.utils.remove_weight_norm(module, name) ウェイト正規化を削除する。
torch.nn.utils.spectral_norm(module, name, n_power_iterations, eps, bias) モジュールパラメータにスペクトル正規化を適用する。
torch.nn.utils.remove_spectral_norm(module, name) スペクトル正規化を削除する。
torch.nn.utils.fuse_conv_bn_eval(conv, bn) 畳み込み層とバッチ正規化層を融合する(推論モード)。
torch.nn.utils.fuse_linear_bn_eval(linear, bn) 線形層とバッチ正規化層を融合する(推論モード)。
torch.nn.utils.skip_init(module_class, *args, **kwargs) パラメータ初期化をスキップする。
torch.nn.utils.parameters_to_vector(parameters) パラメータリストをベクトルにフラット化する。
torch.nn.utils.vector_to_parameters(vector, parameters) ベクトルをパラメータリストに再形成する。

パラメータ初期化(nn.init)

関数 説明
torch.nn.init.zeros_(tensor) テンソルをゼロで初期化する。
torch.nn.init.ones_(tensor) テンソルを1で初期化する。
torch.nn.init.uniform_(tensor, a, b) 一様分布初期化。
torch.nn.init.normal_(tensor, mean, std) 正規分布初期化。
torch.nn.init.constant_(tensor, val) 定数値初期化。
torch.nn.init.eye_(tensor) 単位行列初期化(2次元正方行列のみ)。
torch.nn.init.dirac_(tensor) Diracデルタ初期化(入力チャンネル数を保持)。
torch.nn.init.xavier_uniform_(tensor, gain) Xavier一様分布初期化。
torch.nn.init.xavier_normal_(tensor, gain) Xavier正規分布初期化。
torch.nn.init.kaiming_uniform_(tensor, a, mode, nonlinearity) Kaiming一様分布初期化。ReLU活性化に適している。
torch.nn.init.kaiming_normal_(tensor, a, mode, nonlinearity) Kaiming正規分布初期化。ReLU活性化に適している。
torch.nn.init.trunc_normal_(tensor, mean, std, a, b) 切断正規分布初期化。
torch.nn.init.orthogonal_(tensor, gain) 直交初期化。
torch.nn.init.sparse_(tensor, sparsity, std) スパース初期化(大部分をゼロにする)。
torch.nn.init.calculate_gain(nonlinearity, param) 初期化ゲイン値を計算する。

RNNユーティリティ関数

関数 説明
torch.nn.utils.rnn.PackedSequence シーケンスをパッキングし、可変長シーケンスを処理する。
torch.nn.utils.rnn.pack_padded_sequence(input, lengths, batch_first, enforce_sorted) パディングされたシーケンスをパッキングする。
torch.nn.utils.rnn.pad_packed_sequence(input, batch_first, padding_value, total_length) シーケンスをアンパックする。
torch.nn.utils.rnn.pad_sequence(sequences, batch_first, padding_value) シーケンスを同じ長さにパディングする。
torch.nn.utils.rnn.pack_sequence(sequences, enforce_sorted) シーケンスのリストを直接パッキングする。

剪定関数(Pruning)

関数 説明
torch.nn.utils.prune.random_unstructured(module, name, amount) ランダム非構造化剪定。
torch.nn.utils.prune.l1_unstructured(module, name, amount) L1非構造化剪定。
torch.nn.utils.prune.global_unstructured(parameters, pruning_method, amount) グローバル非構造化剪定。
torch.nn.utils.prune.remove(module, name) 剪定を削除する。
torch.nn.utils.prune.is_pruned(module) モジュールが剪定されているか確認する。

Flatten層

クラス/関数 説明
torch.nn.Flatten(start_dim, end_dim) テンソルをフラット化し、多次元テンソルを2次元に展平する。
torch.nn.Unflatten(dim, unflattened_size) アンフラット化(解展平)し、1次元テンソルを多次元に再整形する。

例

例

import torch
import torch.nn as nn

# シンプルなニューラルネットワークを定義する
class SimpleNet(nn.Module):
    def __init__(self):
        super(SimpleNet, self).__init__()
        self.fc1 = nn.Linear(10, 20)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(20, 1)

    def forward(self, x):
        x = self.fc1(x)
        x = self.relu(x)
        x = self.fc2(x)
        return x

# モデルと入力を生成する
model = SimpleNet()
input = torch.randn(5, 10)
output = model(input)
print(output)

例:CNNを使用した画像分類

import torch
import torch.nn as nn

class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        # 畳み込み層
        self.conv1 = nn.Conv2d(3, 16, kernel_size=3, padding=1)
        self.conv2 = nn.Conv2d(16, 32, kernel_size=3, padding=1)
        self.conv3 = nn.Conv2d(32, 64, kernel_size=3, padding=1)

        # プーリング層
        self.pool = nn.MaxPool2d(2, 2)

        # バッチ正規化
        self.bn1 = nn.BatchNorm2d(16)
        self.bn2 = nn.BatchNorm2d(32)
        self.bn3 = nn.BatchNorm2d(64)

        # 活性化関数
        self.relu = nn.ReLU()

        # 全結合層
        self.fc1 = nn.Linear(64 * 4 * 4, 256)
        self.fc2 = nn.Linear(256, 10)

        # Dropout
        self.dropout = nn.Dropout(0.5)

    def forward(self, x):
        # Conv -> BN -> ReLU -> Pool
        x = self.pool(self.relu(self.bn1(self.conv1(x))))
        x = self.pool(self.relu(self.bn2(self.conv2(x))))
        x = self.pool(self.relu(self.bn3(self.conv3(x))))

        # Flatten
        x = x.view(x.size(0), -1)

        # FC -> ReLU -> Dropout -> FC
        x = self.dropout(self.relu(self.fc1(x)))
        x = self.fc2(x)
        return x

# モデルを作成
model = CNN()
print(model)

# 順伝播をテスト
input_tensor = torch.randn(1, 3, 32, 32)
output = model(input_tensor)
print("Output shape:", output.shape)

例:LSTMを使用したテキスト分類

import torch
import torch.nn as nn

class LSTMClassifier(nn.Module):
    def __init__(self, vocab_size, embedding_dim, hidden_dim, num_layers, output_dim):
        super(LSTMClassifier, self).__init__()

        # 埋め込み層
        self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=0)

        # LSTM層
        self.lstm = nn.LSTM(
            embedding_dim,
            hidden_dim,
            num_layers=num_layers,
            batch_first=True,
            bidirectional=True,
            dropout=0.5
        )

        # 全結合層
        self.fc = nn.Linear(hidden_dim * 2, output_dim)

        # Dropout
        self.dropout = nn.Dropout(0.5)

    def forward(self, text, text_lengths):
        # 埋め込み
        embedded = self.embedding(text)

        # 可変長入力を処理するためにシーケンスをパッキング
        packed = nn.utils.rnn.pack_padded_sequence(
            embedded, text_lengths.cpu(), batch_first=True, enforce_sorted=False
        )

        # LSTM
        packed_output, (hidden, cell) = self.lstm(packed)

        # アンパック
        output, output_lengths = nn.utils.rnn.pad_packed_sequence(packed_output, batch_first=True)

        # 双方向の最終隠れ状態を結合
        hidden = torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim=1)

        # Dropoutと全結合
        hidden = self.dropout(hidden)
        output = self.fc(hidden)

        return output

# パラメータ
vocab_size = 10000
embedding_dim = 128
hidden_dim = 256
num_layers = 2
output_dim = 5  # 5分類

# モデルを作成
model = LSTMClassifier(vocab_size, embedding_dim, hidden_dim, num_layers, output_dim)
print(model)

例:Transformerエンコーダの使用

import torch
import torch.nn as nn

class TransformerClassifier(nn.Module):
    def __init__(self, input_dim, d_model, nhead, num_layers, dim_feedforward, output_dim, dropout):
        super(TransformerClassifier, self).__init__()

        # 埋め込み層
        self.embedding = nn.Linear(input_dim, d_model)

        # 位置エンコーディング
        self.positional_encoding = nn.Parameter(torch.randn(1, 1000, d_model) * 0.1)

        # Transformerエンコーダー層
        encoder_layer = nn.TransformerEncoderLayer(
            d_model=d_model,
            nhead=nhead,
            dim_feedforward=dim_feedforward,
            dropout=dropout,
            batch_first=True
        )

        # Transformerエンコーダー
        self.transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)

        # 分類ヘッド
        self.fc = nn.Linear(d_model, output_dim)
        self.dropout = nn.Dropout(dropout)

    def forward(self, x):
        # 位置エンコーディングを追加
        seq_len = x.size(1)
        x = self.embedding(x) + self.positional_encoding[:, :seq_len, :]

        # Transformerエンコード
        x = self.transformer_encoder(x)

        # 最初の位置の出力を使用して分類(CLSトークンと同様)
        x = x[:, 0, :]

        x = self.dropout(x)
        x = self.fc(x)

        return x

# パラメータ
input_dim = 512
d_model = 512
nhead = 8
num_layers = 6
dim_feedforward = 2048
output_dim = 10
dropout = 0.1

# モデルを作成
model = TransformerClassifier(input_dim, d_model, nhead, num_layers, dim_feedforward, output_dim, dropout)
print(model)

# テスト
x = torch.randn(32, 100, input_dim)  # batch_size=32, seq_len=100
output = model(x)
print("Output shape:", output.shape)  # (32, 10)

より詳細な情報が必要な場合は、以下を参照してくださいPyTorch公式ドキュメント。

その他の拡張