python
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
TransNet V2(Souček & Lokoč 2020、2.1 節・Figure 1)の DDCNN V2 セルと、類似度を除いた小さな形
入力:(B, 3, T, 27, 48) のフレーム 出力:フレームごとの遷移のスコア(2 つの頭)
学習済みのモデルを使うだけなら、公開のコード(github.com/soCzech/TransNetV2)の inference を使う:
model = TransNetV2("/path/to/weights_dir/")
video_frames, single_frame_p, all_frame_p = model.predict_video("/path/to/video.mp4")
"""
class DDCNNV2Cell(nn.Module):
def __init__(self, in_ch, F_, activation=True):
super().__init__()
self.branches = nn.ModuleList()
for d in (1, 2, 4, 8): # 時間方向の拡張率
self.branches.append(nn.Sequential(
nn.Conv3d(in_ch, 2 * F_, (1, 3, 3), padding=(0, 1, 1), bias=False), # 空間の畳み込み
nn.Conv3d(2 * F_, F_, (3, 1, 1), padding=(d, 0, 0), dilation=(d, 1, 1), bias=False), # 時間の畳み込み
))
self.bn = nn.BatchNorm3d(4 * F_, eps=1e-3)
self.activation = activation
def forward(self, x):
x = self.bn(torch.cat([b(x) for b in self.branches], dim=1)) # 4 つの枝をつなぐ:4F チャネル
return F.relu(x) if self.activation else x
class StackedDDCNNV2(nn.Module):
"""セル 2 つ → 1 つ目の出力を足す → 空間の 2×2 平均プーリング"""
def __init__(self, in_ch, F_):
super().__init__()
self.cell1 = DDCNNV2Cell(in_ch, F_)
self.cell2 = DDCNNV2Cell(4 * F_, F_, activation=False)
self.pool = nn.AvgPool3d((1, 2, 2))
def forward(self, x):
shortcut = self.cell1(x)
x = F.relu(self.cell2(shortcut)) + shortcut
return self.pool(x)
class TinyTransNetV2(nn.Module):
def __init__(self, F_=16):
super().__init__()
self.blocks = nn.Sequential(
StackedDDCNNV2(3, F_), # 64 チャネル
StackedDDCNNV2(4 * F_, 2 * F_), # 128 チャネル
StackedDDCNNV2(8 * F_, 4 * F_), # 256 チャネル
)
self.fc = nn.Linear(16 * F_ * 3 * 6, 1024) # 256 × 3 × 6 = 4608(類似度の 128 + 128 は省略)
self.drop = nn.Dropout(0.5)
self.head_single = nn.Linear(1024, 1) # 遷移の中央のフレーム(予測に使う)
self.head_all = nn.Linear(1024, 1) # 遷移のすべてのフレーム(学習のときだけ)
def forward(self, x): # x: (B, 3, T, 27, 48)、値は 0〜1
x = self.blocks(x) # (B, 256, T, 3, 6)
x = x.permute(0, 2, 1, 3, 4).flatten(2) # (B, T, 4608)
x = self.drop(F.relu(self.fc(x)))
return self.head_single(x).squeeze(-1), self.head_all(x).squeeze(-1)
def loss_fn(single, all_, y_single, y_all):
"""遷移の中央のフレームを 5 倍に重み付けし、2 つ目の頭は 0.1 倍(2.2.4 節)"""
l1 = F.binary_cross_entropy_with_logits(single, y_single, pos_weight=torch.tensor(5.0))
l2 = F.binary_cross_entropy_with_logits(all_, y_all)
return l1 + 0.1 * l2
def to_transitions(prob, threshold=0.5):
"""しきい値を超えるフレームが続く所を、1 つの遷移 (始まり, 終わり) にする"""
above = (prob > threshold).tolist()
out, start = [], None
for i, a in enumerate(above + [False]):
if a and start is None:
start = i
elif not a and start is not None:
out.append((start, i - 1))
start = None
return out
model = TinyTransNetV2()
frames = torch.rand(2, 3, 100, 27, 48) # 2 本、100 フレーム、48 × 27 画素
y_single = torch.zeros(2, 100); y_single[:, 50] = 1 # 遷移の中央のフレーム
y_all = torch.zeros(2, 100); y_all[:, 46:55] = 1 # 遷移のすべてのフレーム(9 フレームのディゾルブ)
model.train() # 学習:ドロップアウトとバッチ正規化の統計の更新が働く
optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9, weight_decay=1e-4)
s, a = model(frames)
loss = loss_fn(s, a, y_single, y_all)
optimizer.zero_grad()
loss.backward()
optimizer.step()
model.eval() # 推論:ドロップアウトなし、バッチ正規化は保存した統計を使う
with torch.no_grad():
s, _ = model(frames)
prob = torch.sigmoid(s[0, 25:75]) # 真ん中の 50 フレームだけを使う
print(to_transitions(prob))