PyTorch torch.nn.AdaptiveMaxPool2d 関数
torch.nn.AdaptiveMaxPool2dは PyTorch の適応的最大値プーリングモジュールです。
入力を指定サイズにプーリングし、平均値ではなく最大値を保持します。
関数定義
torch.nn.AdaptiveMaxPool2d(output_size, return_indices=False)
パラメータ
output_size: 出力サイズreturn_indices: インデックスを返すかどうか
使用例
例 1: 基本的な使い方
実例
import torch
import torch.nn as nn
# グローバル最大プーリング
gap = nn.AdaptiveMaxPool2d(1)
# 異なるサイズの入力
x1 = torch.randn(1, 64, 32, 32)
x2 = torch.randn(1, 64, 16, 16)
print("32x32 ->", gap(x1).shape)
print("16x16 ->", gap(x2).shape)
import torch.nn as nn
# グローバル最大プーリング
gap = nn.AdaptiveMaxPool2d(1)
# 異なるサイズの入力
x1 = torch.randn(1, 64, 32, 32)
x2 = torch.randn(1, 64, 16, 16)
print("32x32 ->", gap(x1).shape)
print("16x16 ->", gap(x2).shape)
例 2: インデックスを返す
実例
import torch
import torch.nn as nn
gap = nn.AdaptiveMaxPool2d(1, return_indices=True)
x = torch.randn(1, 64, 8, 8)
output, indices = gap(x)
print("出力形状:", output.shape)
print("インデックス形状:", indices.shape)
print("インデックス値:", indices.item())
import torch.nn as nn
gap = nn.AdaptiveMaxPool2d(1, return_indices=True)
x = torch.randn(1, 64, 8, 8)
output, indices = gap(x)
print("出力形状:", output.shape)
print("インデックス形状:", indices.shape)
print("インデックス値:", indices.item())
例 3: AdaptiveAvgPool2d との比較
実例
import torch
import torch.nn as nn
x = torch.tensor([[[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]]], dtype=torch.float32)
avgpool = nn.AdaptiveAvgPool2d(1)
maxpool = nn.AdaptiveMaxPool2d(1)
print("入力:\n", x[0, 0])
print("平均プーリング:", avgpool(x).item())
print("最大プーリング:", maxpool(x).item())
import torch.nn as nn
x = torch.tensor([[[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]]], dtype=torch.float32)
avgpool = nn.AdaptiveAvgPool2d(1)
maxpool = nn.AdaptiveMaxPool2d(1)
print("入力:\n", x[0, 0])
print("平均プーリング:", avgpool(x).item())
print("最大プーリング:", maxpool(x).item())
使用シーン
- グローバル最大プーリング: 最も顕著な特徴を抽出
- 特徴集約: 重要な情報を保持
- 分類ネットワーク: FC 層の代替
ヒント:最大プーリングは最も顕著な特徴を保持し、平均プーリングはより滑らかです。
その他の拡張
PyTorch torch.nn リファレンスマニュアル