python
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
Two-Stream ConvNets(Simonyan & Zisserman 2014、Figure 1・3.1 節・5 章)の実装例
空間ストリーム:1 枚の RGB フレーム (N, 3, 224, 224)
時間ストリーム:L 組のオプティカルフローを積んだもの (N, 2L, 224, 224)
"""
def stack_flows(flows):
"""式 1:flows は (L, 2, H, W)(各組の横 dx と縦 dy)。
各変位の場から平均ベクトルを引き(カメラの動きを弱める)、2L チャネルに並べる。"""
flows = flows - flows.mean(dim=(2, 3), keepdim=True)
L, _, H, W = flows.shape
return flows.reshape(2 * L, H, W) # チャネルの順は dx_1, dy_1, dx_2, dy_2, ...
class StreamConvNet(nn.Module):
"""CNN-M-2048 に近い形(Figure 1)。時間ストリームは 2 つ目の正規化層を外す(5 章)。"""
def __init__(self, in_ch, num_classes, second_norm=True, p_drop=0.5):
super().__init__()
lrn = lambda: nn.LocalResponseNorm(size=5, alpha=1e-4, beta=0.75, k=2.0) # AlexNet と同じ設定
pool = lambda: nn.MaxPool2d(3, stride=2) # 3×3・ストライド 2
self.features = nn.Sequential(
nn.Conv2d(in_ch, 96, 7, stride=2), nn.ReLU(inplace=True), lrn(), pool(),
nn.Conv2d(96, 256, 5, stride=2, padding=1), nn.ReLU(inplace=True),
lrn() if second_norm else nn.Identity(), pool(),
nn.Conv2d(256, 512, 3, padding=1), nn.ReLU(inplace=True),
nn.Conv2d(512, 512, 3, padding=1), nn.ReLU(inplace=True),
nn.Conv2d(512, 512, 3, padding=1), nn.ReLU(inplace=True), pool(),
)
self.classifier = nn.Sequential(
nn.Flatten(),
nn.LazyLinear(4096), nn.ReLU(inplace=True), nn.Dropout(p_drop), # full6
nn.Linear(4096, 2048), nn.ReLU(inplace=True), nn.Dropout(p_drop), # full7
nn.Linear(2048, num_classes),
)
def forward(self, x):
return self.classifier(self.features(x)) # ソフトマックスの前のスコア
class TwoStream(nn.Module):
def __init__(self, num_classes, L=10):
super().__init__()
self.spatial = StreamConvNet(3, num_classes)
# 一から学習するので強いドロップアウト(論文の Table 1b では 0.9)
self.temporal = StreamConvNet(2 * L, num_classes, second_norm=False, p_drop=0.9)
def forward(self, rgb, flow_stack):
# 後段の融合:2 つのソフトマックスのスコアを平均する(もう 1 つの方法は線形 SVM)
p_spatial = F.softmax(self.spatial(rgb), dim=1)
p_temporal = F.softmax(self.temporal(flow_stack), dim=1)
return (p_spatial + p_temporal) / 2
model = TwoStream(num_classes=101)
model.eval() # ドロップアウトを止める(学習では model.train()。2 つのストリームは別々に学習する)
rgb = torch.randn(2, 3, 224, 224)
flow = torch.stack([stack_flows(torch.randn(10, 2, 224, 224)) for _ in range(2)])
with torch.no_grad():
print(model(rgb, flow).shape) # torch.Size([2, 101])