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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Copyright 2023 LINE Corporation
|
| 3 |
+
LINE Corporation licenses this file to you under the Apache License,
|
| 4 |
+
version 2.0 (the "License"); you may not use this file except in compliance
|
| 5 |
+
with the License. You may obtain a copy of the License at:
|
| 6 |
+
https://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
Unless required by applicable law or agreed to in writing, software
|
| 8 |
+
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
| 9 |
+
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
| 10 |
+
License for the specific language governing permissions and limitations
|
| 11 |
+
under the License.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import print_function
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import inspect
|
| 18 |
+
import os
|
| 19 |
+
import pdb
|
| 20 |
+
import pickle
|
| 21 |
+
import random
|
| 22 |
+
import re
|
| 23 |
+
import shutil
|
| 24 |
+
import time
|
| 25 |
+
from collections import *
|
| 26 |
+
|
| 27 |
+
import ipdb
|
| 28 |
+
import numpy as np
|
| 29 |
+
|
| 30 |
+
# torch
|
| 31 |
+
import torch
|
| 32 |
+
import torch.backends.cudnn as cudnn
|
| 33 |
+
import torch.nn as nn
|
| 34 |
+
import torch.nn.functional as F
|
| 35 |
+
import torch.optim as optim
|
| 36 |
+
import yaml
|
| 37 |
+
from einops import rearrange, reduce, repeat
|
| 38 |
+
from evaluation.classificationMAP import getClassificationMAP as cmAP
|
| 39 |
+
from evaluation.detectionMAP import getSingleStreamDetectionMAP as dsmAP
|
| 40 |
+
from feeders.tools import collate_with_padding_multi_joint
|
| 41 |
+
from model.losses import cross_entropy_loss, mvl_loss
|
| 42 |
+
from sklearn.metrics import f1_score
|
| 43 |
+
|
| 44 |
+
# Custom
|
| 45 |
+
from tensorboardX import SummaryWriter
|
| 46 |
+
from torch.autograd import Variable
|
| 47 |
+
from torch.optim.lr_scheduler import _LRScheduler
|
| 48 |
+
from tqdm import tqdm
|
| 49 |
+
from utils.logger import Logger
|
| 50 |
+
|
| 51 |
+
def remove_prefix_from_state_dict(state_dict, prefix):
|
| 52 |
+
new_state_dict = {}
|
| 53 |
+
for k, v in state_dict.items():
|
| 54 |
+
if k.startswith(prefix):
|
| 55 |
+
new_k = k[len(prefix):] # strip the prefix
|
| 56 |
+
else:
|
| 57 |
+
new_k = k
|
| 58 |
+
new_state_dict[new_k] = v
|
| 59 |
+
return new_state_dict
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def init_seed(seed):
|
| 63 |
+
torch.cuda.manual_seed_all(seed)
|
| 64 |
+
torch.manual_seed(seed)
|
| 65 |
+
np.random.seed(seed)
|
| 66 |
+
random.seed(seed)
|
| 67 |
+
torch.backends.cudnn.deterministic = True
|
| 68 |
+
torch.backends.cudnn.benchmark = False
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def get_parser():
|
| 72 |
+
# parameter priority: command line > config > default
|
| 73 |
+
parser = argparse.ArgumentParser(
|
| 74 |
+
description="Spatial Temporal Graph Convolution Network"
|
| 75 |
+
)
|
| 76 |
+
parser.add_argument(
|
| 77 |
+
"--work-dir",
|
| 78 |
+
default="./work_dir/temp",
|
| 79 |
+
help="the work folder for storing results",
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
parser.add_argument("-model_saved_name", default="")
|
| 83 |
+
parser.add_argument(
|
| 84 |
+
"--config",
|
| 85 |
+
default="./config/nturgbd-cross-view/test_bone.yaml",
|
| 86 |
+
help="path to the configuration file",
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
# processor
|
| 90 |
+
parser.add_argument("--phase", default="train", help="must be train or test")
|
| 91 |
+
|
| 92 |
+
# visulize and debug
|
| 93 |
+
parser.add_argument("--seed", type=int, default=8, help="random seed for pytorch")
|
| 94 |
+
parser.add_argument(
|
| 95 |
+
"--log-interval",
|
| 96 |
+
type=int,
|
| 97 |
+
default=100,
|
| 98 |
+
help="the interval for printing messages (#iteration)",
|
| 99 |
+
)
|
| 100 |
+
parser.add_argument(
|
| 101 |
+
"--save-interval",
|
| 102 |
+
type=int,
|
| 103 |
+
default=2,
|
| 104 |
+
help="the interval for storing models (#iteration)",
|
| 105 |
+
)
|
| 106 |
+
parser.add_argument(
|
| 107 |
+
"--eval-interval",
|
| 108 |
+
type=int,
|
| 109 |
+
default=5,
|
| 110 |
+
help="the interval for evaluating models (#iteration)",
|
| 111 |
+
)
|
| 112 |
+
parser.add_argument(
|
| 113 |
+
"--print-log", type=str2bool, default=True, help="print logging or not"
|
| 114 |
+
)
|
| 115 |
+
parser.add_argument(
|
| 116 |
+
"--show-topk",
|
| 117 |
+
type=int,
|
| 118 |
+
default=[1, 5],
|
| 119 |
+
nargs="+",
|
| 120 |
+
help="which Top K accuracy will be shown",
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
# feeder
|
| 124 |
+
parser.add_argument(
|
| 125 |
+
"--feeder", default="feeder.feeder", help="data loader will be used"
|
| 126 |
+
)
|
| 127 |
+
parser.add_argument(
|
| 128 |
+
"--num-worker",
|
| 129 |
+
type=int,
|
| 130 |
+
default=32,
|
| 131 |
+
help="the number of worker for data loader",
|
| 132 |
+
)
|
| 133 |
+
parser.add_argument(
|
| 134 |
+
"--train-feeder-args",
|
| 135 |
+
default=dict(),
|
| 136 |
+
help="the arguments of data loader for training",
|
| 137 |
+
)
|
| 138 |
+
parser.add_argument(
|
| 139 |
+
"--test-feeder-args",
|
| 140 |
+
default=dict(),
|
| 141 |
+
help="the arguments of data loader for test",
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
# model
|
| 145 |
+
parser.add_argument("--model", default=None, help="the model will be used")
|
| 146 |
+
parser.add_argument(
|
| 147 |
+
"--model-args", type=dict, default=dict(), help="the arguments of model"
|
| 148 |
+
)
|
| 149 |
+
parser.add_argument(
|
| 150 |
+
"--weights", default=None, help="the weights for network initialization"
|
| 151 |
+
)
|
| 152 |
+
parser.add_argument(
|
| 153 |
+
"--ignore-weights",
|
| 154 |
+
type=str,
|
| 155 |
+
default=[],
|
| 156 |
+
nargs="+",
|
| 157 |
+
help="the name of weights which will be ignored in the initialization",
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
# optim
|
| 161 |
+
parser.add_argument(
|
| 162 |
+
"--base-lr", type=float, default=0.01, help="initial learning rate"
|
| 163 |
+
)
|
| 164 |
+
parser.add_argument(
|
| 165 |
+
"--step",
|
| 166 |
+
type=int,
|
| 167 |
+
default=[200],
|
| 168 |
+
nargs="+",
|
| 169 |
+
help="the epoch where optimizer reduce the learning rate",
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
# training
|
| 173 |
+
parser.add_argument(
|
| 174 |
+
"--device",
|
| 175 |
+
type=int,
|
| 176 |
+
default=0,
|
| 177 |
+
nargs="+",
|
| 178 |
+
help="the indexes of GPUs for training or testing",
|
| 179 |
+
)
|
| 180 |
+
parser.add_argument("--optimizer", default="SGD", help="type of optimizer")
|
| 181 |
+
parser.add_argument(
|
| 182 |
+
"--nesterov", type=str2bool, default=False, help="use nesterov or not"
|
| 183 |
+
)
|
| 184 |
+
parser.add_argument(
|
| 185 |
+
"--batch-size", type=int, default=256, help="training batch size"
|
| 186 |
+
)
|
| 187 |
+
parser.add_argument(
|
| 188 |
+
"--test-batch-size", type=int, default=256, help="test batch size"
|
| 189 |
+
)
|
| 190 |
+
parser.add_argument(
|
| 191 |
+
"--start-epoch", type=int, default=0, help="start training from which epoch"
|
| 192 |
+
)
|
| 193 |
+
parser.add_argument(
|
| 194 |
+
"--num-epoch", type=int, default=80, help="stop training in which epoch"
|
| 195 |
+
)
|
| 196 |
+
parser.add_argument(
|
| 197 |
+
"--weight-decay", type=float, default=0.0005, help="weight decay for optimizer"
|
| 198 |
+
)
|
| 199 |
+
# loss
|
| 200 |
+
parser.add_argument("--loss", type=str, default="CE", help="loss type(CE or focal)")
|
| 201 |
+
parser.add_argument(
|
| 202 |
+
"--label_count_path",
|
| 203 |
+
default=None,
|
| 204 |
+
type=str,
|
| 205 |
+
help="Path to label counts (used in loss weighting)",
|
| 206 |
+
)
|
| 207 |
+
parser.add_argument(
|
| 208 |
+
"---beta",
|
| 209 |
+
type=float,
|
| 210 |
+
default=0.9999,
|
| 211 |
+
help="Hyperparameter for Class balanced loss",
|
| 212 |
+
)
|
| 213 |
+
parser.add_argument(
|
| 214 |
+
"--gamma", type=float, default=2.0, help="Hyperparameter for Focal loss"
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
parser.add_argument("--only_train_part", default=False)
|
| 218 |
+
parser.add_argument("--only_train_epoch", default=0)
|
| 219 |
+
parser.add_argument("--warm_up_epoch", default=10)
|
| 220 |
+
|
| 221 |
+
parser.add_argument(
|
| 222 |
+
"--lambda-mil", default=1.0, help="balancing hyper-parameter of mil branch"
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
parser.add_argument(
|
| 226 |
+
"--class-threshold",
|
| 227 |
+
type=float,
|
| 228 |
+
default=0.1,
|
| 229 |
+
help="class threshold for rejection",
|
| 230 |
+
)
|
| 231 |
+
parser.add_argument(
|
| 232 |
+
"--start-threshold",
|
| 233 |
+
type=float,
|
| 234 |
+
default=0.03,
|
| 235 |
+
help="start threshold for action localization",
|
| 236 |
+
)
|
| 237 |
+
parser.add_argument(
|
| 238 |
+
"--end-threshold",
|
| 239 |
+
type=float,
|
| 240 |
+
default=0.055,
|
| 241 |
+
help="end threshold for action localization",
|
| 242 |
+
)
|
| 243 |
+
parser.add_argument(
|
| 244 |
+
"--threshold-interval",
|
| 245 |
+
type=float,
|
| 246 |
+
default=0.005,
|
| 247 |
+
help="threshold interval for action localization",
|
| 248 |
+
)
|
| 249 |
+
parser.add_argument(
|
| 250 |
+
"--knn_k",
|
| 251 |
+
type=float,
|
| 252 |
+
default=50,
|
| 253 |
+
help="threshold interval for action localization",
|
| 254 |
+
)
|
| 255 |
+
parser.add_argument(
|
| 256 |
+
"--knn_t",
|
| 257 |
+
type=float,
|
| 258 |
+
default=0.1,
|
| 259 |
+
help="threshold interval for action localization",
|
| 260 |
+
)
|
| 261 |
+
return parser
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
class Processor:
|
| 265 |
+
"""
|
| 266 |
+
Processor for Skeleton-based Action Recgnition
|
| 267 |
+
"""
|
| 268 |
+
|
| 269 |
+
def __init__(self, arg):
|
| 270 |
+
self.arg = arg
|
| 271 |
+
self.save_arg()
|
| 272 |
+
if arg.phase == "train":
|
| 273 |
+
if not arg.train_feeder_args["debug"]:
|
| 274 |
+
if os.path.isdir(arg.model_saved_name):
|
| 275 |
+
print("log_dir: ", arg.model_saved_name, "already exist")
|
| 276 |
+
# answer = input('delete it? y/n:')
|
| 277 |
+
answer = "y"
|
| 278 |
+
if answer == "y":
|
| 279 |
+
print("Deleting dir...")
|
| 280 |
+
shutil.rmtree(arg.model_saved_name)
|
| 281 |
+
print("Dir removed: ", arg.model_saved_name)
|
| 282 |
+
# input('Refresh the website of tensorboard by pressing any keys')
|
| 283 |
+
else:
|
| 284 |
+
print("Dir not removed: ", arg.model_saved_name)
|
| 285 |
+
self.train_writer = SummaryWriter(
|
| 286 |
+
os.path.join(arg.model_saved_name, "train"), "train"
|
| 287 |
+
)
|
| 288 |
+
self.val_writer = SummaryWriter(
|
| 289 |
+
os.path.join(arg.model_saved_name, "val"), "val"
|
| 290 |
+
)
|
| 291 |
+
else:
|
| 292 |
+
self.train_writer = self.val_writer = SummaryWriter(
|
| 293 |
+
os.path.join(arg.model_saved_name, "test"), "test"
|
| 294 |
+
)
|
| 295 |
+
self.global_step = 0
|
| 296 |
+
self.load_model()
|
| 297 |
+
self.load_optimizer()
|
| 298 |
+
self.load_data()
|
| 299 |
+
self.lr = self.arg.base_lr
|
| 300 |
+
self.best_acc = 0
|
| 301 |
+
self.best_per_class_acc = 0
|
| 302 |
+
self.loss_nce = torch.nn.BCELoss()
|
| 303 |
+
|
| 304 |
+
self.my_logger = Logger(
|
| 305 |
+
os.path.join(arg.model_saved_name, "log.txt"), title="SWTAL"
|
| 306 |
+
)
|
| 307 |
+
self.my_logger.set_names(["Step", "cmap"] + [f"map_0.{i}" for i in range(1, 6)]+["avg"])
|
| 308 |
+
|
| 309 |
+
def load_data(self):
|
| 310 |
+
Feeder = import_class(self.arg.feeder)
|
| 311 |
+
self.data_loader = dict()
|
| 312 |
+
if self.arg.phase == "train":
|
| 313 |
+
self.data_loader["train"] = torch.utils.data.DataLoader(
|
| 314 |
+
dataset=Feeder(**self.arg.train_feeder_args),
|
| 315 |
+
batch_size=1,
|
| 316 |
+
shuffle=True,
|
| 317 |
+
num_workers=self.arg.num_worker,
|
| 318 |
+
drop_last=True,
|
| 319 |
+
collate_fn=collate_with_padding_multi_joint,
|
| 320 |
+
)
|
| 321 |
+
self.data_loader["test"] = torch.utils.data.DataLoader(
|
| 322 |
+
dataset=Feeder(**self.arg.test_feeder_args),
|
| 323 |
+
batch_size=self.arg.test_batch_size,
|
| 324 |
+
shuffle=False,
|
| 325 |
+
num_workers=self.arg.num_worker,
|
| 326 |
+
drop_last=False,
|
| 327 |
+
collate_fn=collate_with_padding_multi_joint,
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
def load_model(self):
|
| 331 |
+
output_device = (
|
| 332 |
+
self.arg.device[0] if type(self.arg.device) is list else self.arg.device
|
| 333 |
+
)
|
| 334 |
+
self.output_device = output_device
|
| 335 |
+
Model = import_class(self.arg.model)
|
| 336 |
+
|
| 337 |
+
shutil.copy2(inspect.getfile(Model), self.arg.work_dir)
|
| 338 |
+
# print(Model)
|
| 339 |
+
self.model = Model(**self.arg.model_args).cuda(output_device)
|
| 340 |
+
|
| 341 |
+
self.loss_type = arg.loss
|
| 342 |
+
|
| 343 |
+
if self.arg.weights:
|
| 344 |
+
self.print_log("Load weights from {}.".format(self.arg.weights))
|
| 345 |
+
if ".pkl" in self.arg.weights:
|
| 346 |
+
with open(self.arg.weights, "r") as f:
|
| 347 |
+
weights = pickle.load(f)
|
| 348 |
+
else:
|
| 349 |
+
weights = torch.load(self.arg.weights)
|
| 350 |
+
|
| 351 |
+
weights = OrderedDict(
|
| 352 |
+
[
|
| 353 |
+
[k.split("module.")[-1], v.cuda(output_device)]
|
| 354 |
+
for k, v in weights.items()
|
| 355 |
+
]
|
| 356 |
+
)
|
| 357 |
+
# print(weights.keys())
|
| 358 |
+
if 'unik' not in self.arg.model:
|
| 359 |
+
print('this is agcn')
|
| 360 |
+
weights = remove_prefix_from_state_dict(weights, 'encoder_q.agcn.')
|
| 361 |
+
|
| 362 |
+
if 'unik' in self.arg.model:
|
| 363 |
+
print('this is unik')
|
| 364 |
+
weights = remove_prefix_from_state_dict(weights, 'encoder_q.unik.')
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
self.arg.ignore_weights = ['data_bn','fc','encoder_q','encoder_k','queue','queue_ptr','value_transform','mask_param']
|
| 368 |
+
|
| 369 |
+
keys = list(weights.keys())
|
| 370 |
+
|
| 371 |
+
for w in self.arg.ignore_weights:
|
| 372 |
+
for key in keys:
|
| 373 |
+
if w in key:
|
| 374 |
+
if weights.pop(key, None) is not None:
|
| 375 |
+
continue
|
| 376 |
+
# self.print_log(
|
| 377 |
+
# "Sucessfully Remove Weights: {}.".format(key)
|
| 378 |
+
# )
|
| 379 |
+
# else:
|
| 380 |
+
# self.print_log("Can Not Remove Weights: {}.".format(key))
|
| 381 |
+
|
| 382 |
+
try:
|
| 383 |
+
self.model.load_state_dict(weights)
|
| 384 |
+
except:
|
| 385 |
+
state = self.model.state_dict()
|
| 386 |
+
# print(state.keys())
|
| 387 |
+
diff = list(set(state.keys()).difference(set(weights.keys())))
|
| 388 |
+
print("Can not find these weights:")
|
| 389 |
+
for d in diff:
|
| 390 |
+
print(" " + d)
|
| 391 |
+
state.update(weights)
|
| 392 |
+
self.model.load_state_dict(state)
|
| 393 |
+
|
| 394 |
+
if type(self.arg.device) is list:
|
| 395 |
+
if len(self.arg.device) > 1:
|
| 396 |
+
self.model = nn.DataParallel(
|
| 397 |
+
self.model, device_ids=self.arg.device, output_device=output_device
|
| 398 |
+
)
|
| 399 |
+
|
| 400 |
+
def load_optimizer(self):
|
| 401 |
+
if self.arg.optimizer == "SGD":
|
| 402 |
+
self.optimizer = optim.SGD(
|
| 403 |
+
self.model.parameters(),
|
| 404 |
+
lr=self.arg.base_lr,
|
| 405 |
+
momentum=0.9,
|
| 406 |
+
nesterov=self.arg.nesterov,
|
| 407 |
+
weight_decay=self.arg.weight_decay,
|
| 408 |
+
)
|
| 409 |
+
elif self.arg.optimizer == "Adam":
|
| 410 |
+
self.optimizer = optim.Adam(
|
| 411 |
+
self.model.parameters(),
|
| 412 |
+
lr=self.arg.base_lr,
|
| 413 |
+
weight_decay=self.arg.weight_decay,
|
| 414 |
+
)
|
| 415 |
+
else:
|
| 416 |
+
raise ValueError()
|
| 417 |
+
|
| 418 |
+
def save_arg(self):
|
| 419 |
+
# save arg
|
| 420 |
+
arg_dict = vars(self.arg)
|
| 421 |
+
if not os.path.exists(self.arg.work_dir):
|
| 422 |
+
os.makedirs(self.arg.work_dir)
|
| 423 |
+
with open("{}/config.yaml".format(self.arg.work_dir), "w") as f:
|
| 424 |
+
yaml.dump(arg_dict, f)
|
| 425 |
+
|
| 426 |
+
def adjust_learning_rate(self, epoch):
|
| 427 |
+
if self.arg.optimizer == "SGD" or self.arg.optimizer == "Adam":
|
| 428 |
+
if epoch < self.arg.warm_up_epoch:
|
| 429 |
+
lr = self.arg.base_lr * (epoch + 1) / self.arg.warm_up_epoch
|
| 430 |
+
else:
|
| 431 |
+
lr = self.arg.base_lr * (
|
| 432 |
+
0.1 ** np.sum(epoch >= np.array(self.arg.step))
|
| 433 |
+
)
|
| 434 |
+
for param_group in self.optimizer.param_groups:
|
| 435 |
+
param_group["lr"] = lr
|
| 436 |
+
|
| 437 |
+
return lr
|
| 438 |
+
else:
|
| 439 |
+
raise ValueError()
|
| 440 |
+
|
| 441 |
+
def print_time(self):
|
| 442 |
+
localtime = time.asctime(time.localtime(time.time()))
|
| 443 |
+
self.print_log("Local current time : " + localtime)
|
| 444 |
+
|
| 445 |
+
def print_log(self, str, print_time=True):
|
| 446 |
+
if print_time:
|
| 447 |
+
localtime = time.asctime(time.localtime(time.time()))
|
| 448 |
+
str = "[ " + localtime + " ] " + str
|
| 449 |
+
print(str)
|
| 450 |
+
if self.arg.print_log:
|
| 451 |
+
with open("{}/print_log.txt".format(self.arg.work_dir), "a") as f:
|
| 452 |
+
print(str, file=f)
|
| 453 |
+
|
| 454 |
+
def record_time(self):
|
| 455 |
+
self.cur_time = time.time()
|
| 456 |
+
return self.cur_time
|
| 457 |
+
|
| 458 |
+
def split_time(self):
|
| 459 |
+
split_time = time.time() - self.cur_time
|
| 460 |
+
self.record_time()
|
| 461 |
+
return split_time
|
| 462 |
+
|
| 463 |
+
@torch.no_grad()
|
| 464 |
+
def build_feature_bank(self):
|
| 465 |
+
self.model.eval()
|
| 466 |
+
self.print_log("Building feature bank...")
|
| 467 |
+
|
| 468 |
+
loader = self.data_loader["train"]
|
| 469 |
+
process = tqdm(self.data_loader['train'])
|
| 470 |
+
|
| 471 |
+
feature_bank = []
|
| 472 |
+
feature_labels = []
|
| 473 |
+
|
| 474 |
+
for batch_idx, (data, label, target, mask, index, soft_label) in enumerate(process):
|
| 475 |
+
data = data.float().cuda(self.output_device)
|
| 476 |
+
target = target.cuda(self.output_device) # [N, T]
|
| 477 |
+
|
| 478 |
+
# 1. 提取特征
|
| 479 |
+
feat = self.model(data) # [N, T, C]
|
| 480 |
+
feat = F.normalize(feat, dim=-1) # 建议归一化
|
| 481 |
+
feat = feat.reshape(-1, feat.size(-1)) # [N*T, C]
|
| 482 |
+
|
| 483 |
+
# 2. 标签展平
|
| 484 |
+
label_flat = target.view(-1) # [N*T]
|
| 485 |
+
|
| 486 |
+
feature_bank.append(feat)
|
| 487 |
+
feature_labels.append(label_flat)
|
| 488 |
+
|
| 489 |
+
# 3. 合并所有帧
|
| 490 |
+
feature_bank = torch.cat(feature_bank, dim=0) # [N_total*T, C]
|
| 491 |
+
feature_labels = torch.cat(feature_labels, dim=0) # [N_total*T]
|
| 492 |
+
|
| 493 |
+
self.feature_bank = feature_bank
|
| 494 |
+
self.feature_labels = feature_labels
|
| 495 |
+
|
| 496 |
+
self.print_log(f"Feature bank size: {feature_bank.shape}")
|
| 497 |
+
self.print_log(f"Label bank size: {feature_labels.shape}")
|
| 498 |
+
|
| 499 |
+
@torch.no_grad()
|
| 500 |
+
def eval(
|
| 501 |
+
self,
|
| 502 |
+
epoch,
|
| 503 |
+
wb_dict,
|
| 504 |
+
loader_name=["test"],
|
| 505 |
+
):
|
| 506 |
+
self.model.eval()
|
| 507 |
+
self.print_log("Eval epoch: {}".format(epoch + 1))
|
| 508 |
+
|
| 509 |
+
vid_preds = []
|
| 510 |
+
frm_preds = []
|
| 511 |
+
vid_lens = []
|
| 512 |
+
labels = []
|
| 513 |
+
|
| 514 |
+
for ln in loader_name:
|
| 515 |
+
loss_value = []
|
| 516 |
+
step = 0
|
| 517 |
+
process = tqdm(self.data_loader[ln])
|
| 518 |
+
|
| 519 |
+
for batch_idx, (data, label, target, mask, index, soft_label) in enumerate(
|
| 520 |
+
process
|
| 521 |
+
):
|
| 522 |
+
data = data.float().cuda(self.output_device)
|
| 523 |
+
label = label.cuda(self.output_device)
|
| 524 |
+
mask = mask.cuda(self.output_device)
|
| 525 |
+
|
| 526 |
+
ab_labels = torch.cat([label, torch.ones(label.size(0), 1).cuda()], -1)
|
| 527 |
+
|
| 528 |
+
# forward
|
| 529 |
+
with torch.no_grad():
|
| 530 |
+
features = self.model(data) # shape: [N, T, C_feat]
|
| 531 |
+
features = F.normalize(features, dim=-1) # 单位化(建议)
|
| 532 |
+
|
| 533 |
+
n, t, c = features.shape
|
| 534 |
+
features_flat = features.view(n * t, c) # shape: [N*T, C_feat]
|
| 535 |
+
# 使用 knn_predict(你贴的函数)
|
| 536 |
+
pred_scores = knn_predict(
|
| 537 |
+
features_flat, # [N*T, C_feat]
|
| 538 |
+
self.feature_bank.T, # [C_feat, N_bank*T]
|
| 539 |
+
self.feature_labels, # [N_bank*T]
|
| 540 |
+
classes=5, # 根据你的任务类别数
|
| 541 |
+
knn_k=self.arg.knn_k ,
|
| 542 |
+
knn_t=self.arg.knn_t
|
| 543 |
+
) # 输出 [N*T, topk],取 [:, 0] 是 top-1
|
| 544 |
+
|
| 545 |
+
# pred_top1 = pred_labels[:, 0] # [N*T]
|
| 546 |
+
# # 变为 one-hot logits,模拟 frm_scrs 原始格式
|
| 547 |
+
# frm_scrs_re = F.one_hot(pred_top1, num_classes=5).float() # [N*T, C]
|
| 548 |
+
# frm_scrs = frm_scrs_re.view(n, t, -1) # [N, T, C]
|
| 549 |
+
frm_scrs = pred_scores.view(n, t, -1) # [N, T, C]
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
'''Loc LOSS'''
|
| 553 |
+
target = target.cuda(self.output_device)
|
| 554 |
+
''' into one hot'''
|
| 555 |
+
ground_truth_flat = target.view(-1)
|
| 556 |
+
one_hot_ground_truth = F.one_hot(ground_truth_flat, num_classes=5)
|
| 557 |
+
''' into one hot'''
|
| 558 |
+
frm_scrs_re = rearrange(frm_scrs, "n t c -> (n t) c")
|
| 559 |
+
'''Loc LOSS'''
|
| 560 |
+
'''Loc LOSS'''
|
| 561 |
+
loss = cross_entropy_loss(
|
| 562 |
+
frm_scrs_re, one_hot_ground_truth
|
| 563 |
+
)
|
| 564 |
+
'''Loc LOSS'''
|
| 565 |
+
|
| 566 |
+
loss_value.append(loss.data.item())
|
| 567 |
+
|
| 568 |
+
for i in range(data.size(0)):
|
| 569 |
+
frm_scr = frm_scrs[i]
|
| 570 |
+
|
| 571 |
+
label_ = label[i].cpu().numpy()
|
| 572 |
+
mask_ = mask[i].cpu().numpy()
|
| 573 |
+
vid_len = mask_.sum()
|
| 574 |
+
|
| 575 |
+
frm_pred = F.softmax(frm_scr, -1).cpu().numpy()[:vid_len]
|
| 576 |
+
# vid_pred = vid_pred.cpu().numpy()
|
| 577 |
+
|
| 578 |
+
vid_pred = 0
|
| 579 |
+
vid_preds.append(vid_pred)
|
| 580 |
+
frm_preds.append(frm_pred)
|
| 581 |
+
vid_lens.append(vid_len)
|
| 582 |
+
labels.append(label_)
|
| 583 |
+
|
| 584 |
+
step += 1
|
| 585 |
+
|
| 586 |
+
vid_preds = np.array(vid_preds)
|
| 587 |
+
frm_preds = np.array(frm_preds)
|
| 588 |
+
vid_lens = np.array(vid_lens)
|
| 589 |
+
labels = np.array(labels)
|
| 590 |
+
|
| 591 |
+
# cmap = cmAP(vid_preds, labels)
|
| 592 |
+
cmap = 0
|
| 593 |
+
score = cmap
|
| 594 |
+
loss = np.mean(loss_value)
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
dmap, iou = dsmAP(
|
| 598 |
+
vid_preds,
|
| 599 |
+
frm_preds,
|
| 600 |
+
vid_lens,
|
| 601 |
+
self.arg.test_feeder_args["data_path"],
|
| 602 |
+
self.arg,
|
| 603 |
+
multi=True,
|
| 604 |
+
knn=True
|
| 605 |
+
)
|
| 606 |
+
|
| 607 |
+
for iou_val, dmap_val in zip(iou, dmap):
|
| 608 |
+
if isinstance(dmap_val, list):
|
| 609 |
+
try:
|
| 610 |
+
score_strs = []
|
| 611 |
+
for v in dmap_val:
|
| 612 |
+
if isinstance(v, (int, float, np.float32, np.float64)):
|
| 613 |
+
score_strs.append("%.2f" % (100 * v))
|
| 614 |
+
else:
|
| 615 |
+
score_strs.append("n/a")
|
| 616 |
+
score_str = ", ".join(score_strs)
|
| 617 |
+
except Exception as e:
|
| 618 |
+
score_str = "ERROR: " + str(e)
|
| 619 |
+
else:
|
| 620 |
+
score_str = "%.2f" % (100 * dmap_val)
|
| 621 |
+
mAP = "%.2f" % (100 * np.mean(dmap_val))
|
| 622 |
+
print("Detection map @ %.1f = %s" % (iou_val, score_str))
|
| 623 |
+
self.print_log("Detection map @ %.1f = %s" % (iou_val, score_str))
|
| 624 |
+
self.print_log("Detection map @ %.1f = %s" % (iou_val, mAP))
|
| 625 |
+
|
| 626 |
+
flat_dmap = []
|
| 627 |
+
for x in dmap:
|
| 628 |
+
if isinstance(x, list):
|
| 629 |
+
flat_dmap.extend(x)
|
| 630 |
+
else:
|
| 631 |
+
flat_dmap.append(x)
|
| 632 |
+
dmap = flat_dmap
|
| 633 |
+
|
| 634 |
+
print("Avg mAP %.2f" % (100 * np.mean(dmap)))
|
| 635 |
+
self.print_log("Avg mAP %.2f"% (100 * np.mean(dmap)))
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
wb_dict["val loss"] = loss
|
| 639 |
+
wb_dict["val acc"] = score
|
| 640 |
+
|
| 641 |
+
if score > self.best_acc:
|
| 642 |
+
self.best_acc = score
|
| 643 |
+
|
| 644 |
+
print("Acc score: ", score, " model: ", self.arg.model_saved_name)
|
| 645 |
+
if self.arg.phase == "train":
|
| 646 |
+
self.val_writer.add_scalar("loss", loss, self.global_step)
|
| 647 |
+
self.val_writer.add_scalar("acc", score, self.global_step)
|
| 648 |
+
|
| 649 |
+
self.print_log(
|
| 650 |
+
"\tMean {} loss of {} batches: {}.".format(
|
| 651 |
+
ln, len(self.data_loader[ln]), np.mean(loss_value)
|
| 652 |
+
)
|
| 653 |
+
)
|
| 654 |
+
self.print_log("\tAcc score: {:.3f}%".format(score))
|
| 655 |
+
|
| 656 |
+
return wb_dict, np.mean(dmap)
|
| 657 |
+
|
| 658 |
+
def start(self):
|
| 659 |
+
best_map = 0
|
| 660 |
+
best_epoch = 0
|
| 661 |
+
wb_dict = {}
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
self.build_feature_bank()
|
| 665 |
+
wb_dict,map = self.eval(0, wb_dict, loader_name=["test"])
|
| 666 |
+
if map>best_map:
|
| 667 |
+
best_map = map
|
| 668 |
+
best_epoch = 0
|
| 669 |
+
# Log stats. for this epoch
|
| 670 |
+
print("Epoch: {0}\nMetrics: {1}".format(0, wb_dict))
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def str2bool(v):
|
| 675 |
+
if v.lower() in ("yes", "true", "t", "y", "1"):
|
| 676 |
+
return True
|
| 677 |
+
elif v.lower() in ("no", "false", "f", "n", "0"):
|
| 678 |
+
return False
|
| 679 |
+
else:
|
| 680 |
+
raise argparse.ArgumentTypeError("Boolean value expected.")
|
| 681 |
+
|
| 682 |
+
def knn_predict(feature, feature_bank, feature_labels, classes, knn_k, knn_t):
|
| 683 |
+
# compute cos similarity between each feature vector and feature bank ---> [B, N]
|
| 684 |
+
sim_matrix = torch.mm(feature, feature_bank)
|
| 685 |
+
# [B, K]
|
| 686 |
+
sim_weight, sim_indices = sim_matrix.topk(k=knn_k, dim=-1)
|
| 687 |
+
# [B, K]
|
| 688 |
+
sim_labels = torch.gather(feature_labels.expand(feature.size(0), -1), dim=-1, index=sim_indices)
|
| 689 |
+
sim_weight = (sim_weight / knn_t).exp()
|
| 690 |
+
|
| 691 |
+
# counts for each class
|
| 692 |
+
one_hot_label = torch.zeros(feature.size(0) * knn_k, classes, device=sim_labels.device)
|
| 693 |
+
# [B*K, C]
|
| 694 |
+
one_hot_label = one_hot_label.scatter(dim=-1, index=sim_labels.view(-1, 1), value=1.0)
|
| 695 |
+
# weighted score ---> [B, C]
|
| 696 |
+
pred_scores = torch.sum(one_hot_label.view(feature.size(0), -1, classes) * sim_weight.unsqueeze(dim=-1), dim=1)
|
| 697 |
+
|
| 698 |
+
pred_labels = pred_scores.argsort(dim=-1, descending=True)
|
| 699 |
+
# return pred_labels
|
| 700 |
+
return pred_scores
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
def import_class(name):
|
| 704 |
+
components = name.split(".")
|
| 705 |
+
mod = __import__(components[0])
|
| 706 |
+
for comp in components[1:]:
|
| 707 |
+
mod = getattr(mod, comp)
|
| 708 |
+
return mod
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
if __name__ == "__main__":
|
| 712 |
+
parser = get_parser()
|
| 713 |
+
|
| 714 |
+
# load arg form config file
|
| 715 |
+
p = parser.parse_args()
|
| 716 |
+
if p.config is not None:
|
| 717 |
+
with open(p.config, "r") as f:
|
| 718 |
+
default_arg = yaml.safe_load(f)
|
| 719 |
+
key = vars(p).keys()
|
| 720 |
+
for k in default_arg.keys():
|
| 721 |
+
if k not in key:
|
| 722 |
+
print("WRONG ARG: {}".format(k))
|
| 723 |
+
assert k in key
|
| 724 |
+
parser.set_defaults(**default_arg)
|
| 725 |
+
|
| 726 |
+
arg = parser.parse_args()
|
| 727 |
+
print("BABEL Action Recognition")
|
| 728 |
+
print("Config: ", arg)
|
| 729 |
+
init_seed(arg.seed)
|
| 730 |
+
processor = Processor(arg)
|
| 731 |
+
processor.start()
|