Repository: open-mmlab/mmaction2

Issue:
Error in --validate while training.
Hi,

My dataset is multiclass `VideoDataset` type and looks something like this.
```

        some/path/000.mp4 1 3 5
        some/path/001.mp4 1 2
        some/path/002.mp4 2 6 10

```
Given video data and multi-class, I adopted my configs to test something on a small dataset from `tsn_r50_video_1x1x8_100e_kinetics400_rgb.py` and `tsn_r101_1x1x5_50e_mmit_rgb.py` 

It looks something like this
```
# model settings
model = dict(
    type='Recognizer2D',
    backbone=dict(
        type='ResNet',
        pretrained='torchvision://resnet50',
        depth=50,
        norm_eval=False),
    cls_head=dict(
        type='TSNHead',
        num_classes=14,
        in_channels=2048,
        spatial_type='avg',
        consensus=dict(type='AvgConsensus', dim=1),
        loss_cls=dict(type='BCELossWithLogits', loss_weight=160.0),
        dropout_ratio=0.5,
        init_std=0.01,
        multi_class=True,
        label_smooth_eps=0))
# model training and testing settings
train_cfg = None
test_cfg = dict(average_clips=None)
# dataset settings
dataset_type = 'VideoDataset'
data_root = '/home/rajawat/Desktop/videos'
data_root_val = '/home/rajawat/Desktop/val_videos'
ann_file_train = '/home/rajawat/Desktop/labels/train.txt'
ann_file_val = '/home/rajawat/Desktop/labels/val.txt'
ann_file_test = '/home/rajawat/Desktop/labels/test.txt'
img_norm_cfg = dict(
    mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_bgr=False)
train_pipeline = [
    dict(type='DecordInit'),
    dict(type='SampleFrames', clip_len=1, frame_interval=1, num_clips=3),
    dict(type='DecordDecode'),
    dict(type='RandomResizedCrop'),
    dict(type='Resize', scale=(224, 224), keep_ratio=False),
    dict(type='Flip', flip_ratio=0.5),
    dict(type='Normalize', **img_norm_cfg),
    dict(type='FormatShape', input_format='NCHW'),
    dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
    dict(type='ToTensor', keys=['imgs', 'label'])
]
val_pipeline = [
    dict(type='DecordInit'),
    dict(
        type='SampleFrames',
        clip_len=1,
        frame_interval=1,
        num_clips=3,
        test_mode=True),
    dict(type='DecordDecode'),
    dict(type='Resize', scale=(-1, 256)),
    dict(type='CenterCrop', crop_size=224),
    dict(type='Flip', flip_ratio=0),
    dict(type='Normalize', **img_norm_cfg),
    dict(type='FormatShape', input_format='NCHW'),
    dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
    dict(type='ToTensor', keys=['imgs'])
]
test_pipeline = [
    dict(type='DecordInit'),
    dict(
        type='SampleFrames',
        clip_len=1,
        frame_interval=1,
        num_clips=25,
        test_mode=True),
    dict(type='DecordDecode'),
    dict(type='Resize', scale=(-1, 256)),
    dict(type='TenCrop', crop_size=224),
    dict(type='Flip', flip_ratio=0),
    dict(type='Normalize', **img_norm_cfg),
    dict(type='FormatShape', input_format='NCHW'),
    dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
    dict(type='ToTensor', keys=['imgs'])
]

data = dict(
    videos_per_gpu=2,
    workers_per_gpu=0,
    train=dict(
        type=dataset_type,
        ann_file=ann_file_train,
        data_prefix=data_root,
        pipeline=train_pipeline,
        multi_class=True,
        num_classes=14),
    val=dict(
        type=dataset_type,
        ann_file=ann_file_val,
        data_prefix=data_root_val,
        pipeline=val_pipeline,
        multi_class=True,
        num_classes=14),
    test=dict(
        type=dataset_type,
        ann_file=ann_file_test,
        data_prefix=data_root_val,
        pipeline=test_pipeline,
        multi_class=True,
        num_classes=14))
# optimizer
optimizer = dict(
    type='SGD',
    constructor='TSMOptimizerConstructor',
    paramwise_cfg=dict(fc_lr5=True),
    lr=0.01,  # this lr is used for 8 gpus
    momentum=0.9,
    weight_decay=0.0001,
)
optimizer_config = dict(grad_clip=dict(max_norm=20, norm_type=2))
# learning policy
lr_config = dict(policy='step', step=[20, 40])
total_epochs = 10
checkpoint_config = dict(interval=5)
evaluation = dict(interval=2, metrics=['mean_average_precision'])
# yapf:disable
log_config = dict(
    interval=2,
    hooks=[
        dict(type='TextLoggerHook'),
        # dict(type='TensorboardLoggerHook'),
    ])
# runtime settings
dist_params = dict(backend='nccl')
log_level = 'INFO'
work_dir = './work_dirs/tsn_r101_1x1x5_50e_mmit_rgb/'
load_from = None
resume_from = None
workflow = [('train', 1)]

```

while training 
`python tools/train.py configs/recognition/tsn/tsn_r50_1x1x5_50e_cater_rgb.py  --gpus 1` works well , but with `--validate` it breaks down. 

```
Traceback (most recent call last):
  File "tools/train.py", line 178, in <module>
    main()
  File "tools/train.py", line 174, in main
    meta=meta)
  File "/home/rajawat/Desktop/mmaction/apis/train.py", line 156, in train_model
    runner.run(data_loaders, cfg.workflow, cfg.total_epochs, **runner_kwargs)
  File "/home/rajawat/anaconda3/envs/slowfast/lib/python3.7/site-packages/mmcv/runner/epoch_based_runner.py", line 125, in run
    epoch_runner(data_loaders[i], **kwargs)
  File "/home/rajawat/anaconda3/envs/slowfast/lib/python3.7/site-packages/mmcv/runner/epoch_based_runner.py", line 54, in train
    self.call_hook('after_train_epoch')
  File "/home/rajawat/anaconda3/envs/slowfast/lib/python3.7/site-packages/mmcv/runner/base_runner.py", line 308, in call_hook
    getattr(hook, fn_name)(self)
  File "/home/rajawat/Desktop/mmaction/core/evaluation/eval_hooks.py", line 152, in after_train_epoch
    key_score = self.evaluate(runner, results)
  File "/home/rajawat/Desktop/mmaction/core/evaluation/eval_hooks.py", line 170, in evaluate
    results, logger=runner.logger, **self.eval_kwargs)
  File "/home/rajawat/Desktop/mmaction/datasets/base.py", line 215, in evaluate
    for label in gt_labels
  File "/home/rajawat/Desktop/mmaction/datasets/base.py", line 215, in <listcomp>
    for label in gt_labels
  File "/home/rajawat/Desktop/mmaction/datasets/base.py", line 121, in label2array
    arr[label] = 1.
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

```
Am I missing something in the config?
Thanks in advance.


Discussion:

Resolving patch:
diff --git a/mmaction/datasets/video_dataset.py b/mmaction/datasets/video_dataset.py
--- a/mmaction/datasets/video_dataset.py
+++ b/mmaction/datasets/video_dataset.py
@@ -1,7 +1,5 @@
 import os.path as osp
 
-import torch
-
 from .base import BaseDataset
 from .registry import DATASETS
 
@@ -53,15 +51,10 @@ def load_annotations(self):
                     assert self.num_classes is not None
                     filename, label = line_split[0], line_split[1:]
                     label = list(map(int, label))
-                    onehot = torch.zeros(self.num_classes)
-                    onehot[label] = 1.0
                 else:
                     filename, label = line_split
                     label = int(label)
                 if self.data_prefix is not None:
                     filename = osp.join(self.data_prefix, filename)
-                video_infos.append(
-                    dict(
-                        filename=filename,
-                        label=onehot if self.multi_class else label))
+                video_infos.append(dict(filename=filename, label=label))
         return video_infos


Test patch:
diff --git a/tests/data/annotations/video_test_list_multi_label.txt b/tests/data/annotations/video_test_list_multi_label.txt
new file mode 100644
--- /dev/null
+++ b/tests/data/annotations/video_test_list_multi_label.txt
@@ -0,0 +1,2 @@
+test.mp4 0 3
+test.mp4 0 2 4
diff --git a/tests/test_data/test_datasets/base.py b/tests/test_data/test_datasets/base.py
--- a/tests/test_data/test_datasets/base.py
+++ b/tests/test_data/test_datasets/base.py
@@ -41,6 +41,8 @@ def setup_class(cls):
                                               'rawvideo_test_anno.txt')
         cls.video_ann_file = osp.join(cls.ann_file_prefix,
                                       'video_test_list.txt')
+        cls.video_ann_file_multi_label = osp.join(
+            cls.ann_file_prefix, 'video_test_list_multi_label.txt')
 
         # pipeline configuration
         cls.action_pipeline = []
diff --git a/tests/test_data/test_datasets/test_video_dataset.py b/tests/test_data/test_datasets/test_video_dataset.py
--- a/tests/test_data/test_datasets/test_video_dataset.py
+++ b/tests/test_data/test_datasets/test_video_dataset.py
@@ -28,6 +28,24 @@ def test_video_dataset(self):
         assert video_infos == [dict(filename=video_filename, label=0)] * 2
         assert video_dataset.start_index == 0
 
+    def test_video_dataset_multi_label(self):
+        video_dataset = VideoDataset(
+            self.video_ann_file_multi_label,
+            self.video_pipeline,
+            data_prefix=self.data_prefix,
+            multi_class=True,
+            num_classes=100)
+        video_infos = video_dataset.video_infos
+        video_filename = osp.join(self.data_prefix, 'test.mp4')
+        label0 = [0, 3]
+        label1 = [0, 2, 4]
+        labels = [label0, label1]
+        for info, label in zip(video_infos, labels):
+            print(info, video_filename)
+            assert info['filename'] == video_filename
+            assert set(info['label']) == set(label)
+        assert video_dataset.start_index == 0
+
     def test_video_pipeline(self):
         target_keys = ['filename', 'label', 'start_index', 'modality']