PyTorch torch.nn.Conv3d 関数

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


torch.nn.Conv3dPyTorch の3次元畳み込みモジュールです。

3次元入力(深さ x 高さ x 幅)を処理します。例えば、動画や医用画像などです。

関数定義

torch.nn.Conv3d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)

入力形状

(batch, channels, depth, height, width)

使用例

例1: 基本的な使い方

実例

import torch
import torch.nn as nn

# 3D 畳み込み
conv3d = nn.Conv3d(in_channels=3, out_channels=32, kernel_size=3, padding=1)

# 入力: batch=2, チャンネル=3, 深さ=16, 高さ=32, 幅=32
x = torch.randn(2, 3, 16, 32, 32)
output = conv3d(x)

print("入力形状:", x.shape)
print("出力形状:", output.shape)

例2:動画分類

実例

import torch
import torch.nn as nn

class VideoCNN(nn.Module):
    def __init__(self, num_classes=10):
        super(VideoCNN, self).__init__()
        self.conv1 = nn.Conv3d(3, 32, kernel_size=3, padding=1)
        self.pool = nn.MaxPool3d(2)
        self.conv2 = nn.Conv3d(32, 64, kernel_size=3, padding=1)
        self.gap = nn.AdaptiveAvgPool3d(1)
        self.fc = nn.Linear(64, num_classes)

    def forward(self, x):
        x = torch.relu(self.conv1(x))
        x = self.pool(x)
        x = torch.relu(self.conv2(x))
        x = self.gap(x)
        x = x.view(x.size(0), -1)
        return self.fc(x)

model = VideoCNN()
x = torch.randn(4, 3, 16, 112, 112)  # 16フレームの動画
output = model(x)

print("動画:", x.shape, "-> カテゴリ:", output.shape)

例3: パラメータ計算

実例

import torch
import torch.nn as nn

conv = nn.Conv3d(64, 128, kernel_size=3, padding=1)

# パラメータ数計算: out_ch * in_ch * k_d * k_h * k_w + bias
params = 128 * 64 * 3 * 3 * 3
print("パラメータ数:", params)
print("重み形状:", conv.weight.shape)

使用シーン

  • 動画処理: アクション認識
  • 医用画像: CT、MRI
  • 3D セグメンテーション: ボクセルデータ

注意: 3D 畳み込みは計算量が多く、多くのVRAMが必要です。


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

その他の拡張