python コピー
import os
import numpy as np
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader, Dataset
"""
MS-TCN の著者が配っている形の Breakfast(data/breakfast/)を読み込む
features/<動画>.npy : I3D の特徴量。形は [2048, フレーム数](15 fps)
groundTruth/<動画>.txt : 1 行に 1 フレームのクラス名(粗い行動、無音の SIL を含む)
mapping.txt : 「番号 クラス名」の対応
splits/train.split1.bundle・test.split1.bundle : 動画の一覧。分割は 1〜4(人のグループで分ける)
"""
ROOT = 'data/breakfast'
def read_lines(path):
with open(path) as f:
return [line for line in f.read().split('\n') if line]
actions = dict((name, int(idx)) for idx, name in (line.split() for line in read_lines(os.path.join(ROOT, 'mapping.txt'))))
print(len(actions)) # クラス数は mapping.txt で確かめる
class Breakfast(Dataset):
def __init__(self, split=1, train=True):
name = ('train' if train else 'test') + '.split%d.bundle' % split
self.videos = read_lines(os.path.join(ROOT, 'splits', name))
def __len__(self):
return len(self.videos)
def __getitem__(self, i):
vid = self.videos[i].split('.')[0]
feats = np.load(os.path.join(ROOT, 'features', vid + '.npy')) # [2048, T]
labels = [actions[c] for c in read_lines(os.path.join(ROOT, 'groundTruth', vid + '.txt'))]
t = min(feats.shape[1], len(labels)) # 特徴量とラベルの長さを短いほうにそろえる
return torch.from_numpy(feats[:, :t]).float(), torch.tensor(labels[:t])
def collate(batch):
# 動画ごとに長さが違うので、長いほうに合わせて詰め、詰めた所はラベルを -100(損失で無視)にする
t_max = max(x.shape[1] for x, _ in batch)
feats = torch.stack([F.pad(x, (0, t_max - x.shape[1])) for x, _ in batch])
labels = torch.stack([F.pad(y, (0, t_max - y.shape[0]), value=-100) for _, y in batch])
return feats, labels
def segments(labels):
# フレームごとのラベルを(クラス, 開始, 終了)の区間の並びに直す。F1@k と Edit score はこの並びで数える
out, start = [], 0
for t in range(1, len(labels) + 1):
if t == len(labels) or labels[t] != labels[start]:
out.append((int(labels[start]), start, t))
start = t
return out
# 4 つの分割で学習と評価を繰り返し、結果を平均する
for split in range(1, 5):
train_loader = DataLoader(Breakfast(split, train=True), batch_size=1, shuffle=True, collate_fn=collate)
test_loader = DataLoader(Breakfast(split, train=False), batch_size=1, collate_fn=collate)
# model.train() で学習し、model.eval() と torch.no_grad() で test_loader を評価する