File size: 7,200 Bytes
c94c8c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import os
import json
import collections
from pathlib import Path

import numpy as np
import torch

from data.data_utils import Hypo3DAnswer
from evaluator.build import EVALUATOR_REGISTRY


@EVALUATOR_REGISTRY.register()
class Hypo3DEval():
    # 0: what, 1: is, 2: how, 3: can, 4: which, 5: others
    def __init__(self, cfg, task_name):
        self.eval_dict = {
            'target_metric': [], 'ans1_acc': [], 'ans10_acc': [],'non_color_ans1_acc': [], 'non_color_ans10_acc': [],
            'type0_acc': [], 'type1_acc': [], 'type2_acc': [],
            'type0_acc': [], 'type1_acc': [], 'type2_acc': [],
            'type3_acc': [], 'type4_acc': [], 'type5_acc': []
        }
        # run
        self.total_count = 0
        self.non_color_total_count = 0
        
        self.type_count = {
            'type0_count': 1e-10, 'type1_count': 1e-10, 'type2_count': 1e-10,
            'type3_count': 1e-10, 'type4_count': 1e-10, 'type5_count': 1e-10
        }
        self.best_result = -np.inf
        self.base_dir = cfg.data.scan_family_base

        answer_data = json.load(
            open(os.path.join(self.base_dir,
                              'annotations/hypo3d_task/answer_dict.json'), encoding='utf-8')
        )[0]
        answer_counter = []
        for data in answer_data.keys():
            answer_counter.append(data)
            
        answer_counter = collections.Counter(sorted(answer_counter))
        answer_cands = answer_counter.keys()
        self.answer_vocab = Hypo3DAnswer(answer_cands)
        color_terms = [
            "black",
            "blue",
            "brown",
            "cyan",
            "gray",
            "green",
            "grey",
            "orange",
            "pink",
            "purple",
            "red",
            "tan",
            "white",
            "yellow"
        ]
        self.color_ids = [answer_data[name] for name in color_terms]
        self.save = cfg.eval.save
        if self.save:
            self.eval_results = []
            self.save_dir = Path(cfg.exp_dir) / "eval_results" / task_name
            self.save_dir.mkdir(parents=True, exist_ok=True)

    def update(self, data_dict):
        metrics = self.batch_metrics(data_dict)
        batch_count = metrics['total_count']
        self.total_count += batch_count
        non_color_batch_count = metrics['non_color_total_count']
        self.non_color_total_count += non_color_batch_count
        for key in metrics:
            if 'type' in key and 'count' in key:
                self.type_count[key] += metrics[key]

        if self.save:
            for i in range(metrics["total_count"]):
                self.eval_results.append({
                    # vision
                    "source": data_dict['source'][i],
                    "scan_id": data_dict['scan_id'][i],
                    "anchor": data_dict['anchor_locs'][i],
                    'anchor_ort': data_dict['anchor_orientation'][i],
                    # language
                    "instruction": data_dict['prompt_after_obj'][i],
                    "response_gt": data_dict['answer_list'][i].split('[answer_seq]'),
                    "response_pred": data_dict['output_text'][i]
                })

        # save eval dict
        for key in self.eval_dict.keys():
            if 'type' in key:
                # self.eval_dict[key].append(float(metrics[key]) * metrics['type' + key[4] + '_count'])
                continue
            elif 'non_color' not in key:
                self.eval_dict[key].append(float(metrics[key]) * batch_count)
            else:
                self.eval_dict[key].append(float(metrics[key]) * non_color_batch_count)
                
    def batch_metrics(self, data_dict):
        metrics = {}

        # ans
        choice_1 = data_dict['answer_scores'].argmax(dim=-1)
        choice_10 = torch.topk(data_dict['answer_scores'].detach(), 10, -1)[1]
        correct1 = 0
        correct10 = 0
        
        non_color_correct1 = 0
        non_color_correct10 = 0
        total_non_color = 0
        
        # correct_type = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
        count_type = {0: 1e-10, 1: 1e-10, 2: 1e-10, 3: 1e-10, 4: 1e-10, 5: 1e-10}
        for i in range(data_dict['answer_label'].shape[0]):
            gt_id = data_dict['answer_label'][i].argmax().item()
            if gt_id not in self.color_ids:
                total_non_color += 1
                
            # count_type[data_dict['hypo3d_type'][i].item()] += 1
            if data_dict['answer_label'][i, choice_1[i]] == 1:
                if choice_1[i] not in self.color_ids:
                    non_color_correct1 += 1
                correct1 += 1
                # correct_type[data_dict['hypo3d_type'][i].item()] += 1
            for j in range(10):
                if data_dict['answer_label'][i, choice_10[i, j]] == 1:
                    if choice_10[i,j] not in self.color_ids:
                        non_color_correct10 += 1
                    correct10 += 1
                    break
        metrics['ans1_acc'] = correct1 / float(len(choice_1))
        metrics['ans10_acc'] = correct10 / float(len(choice_1))
        
        metrics['non_color_ans1_acc'] = non_color_correct1 / float(total_non_color)
        metrics['non_color_ans10_acc'] = non_color_correct10 / float(total_non_color)
        
        # question type acc
        # for key in count_type.keys():
        #     # metrics['type' + str(key) + '_acc'] = correct_type[key] / count_type[key]
        #     metrics['type' + str(key) + '_count'] = count_type[key]

        metrics['target_metric'] = metrics['ans1_acc']
        metrics["total_count"] = data_dict["answer_scores"].shape[0]
        metrics["non_color_total_count"] = total_non_color
        return metrics

    def reset(self):
        for key in self.eval_dict.keys():
            self.eval_dict[key] = []
        self.total_count = 0
        self.non_color_total_count = 0
        self.type_count = {
            'type0_count': 1e-10, 'type1_count': 1e-10, 'type2_count': 1e-10, 
            'type3_count': 1e-10, 'type4_count': 1e-10, 'type5_count': 1e-10
        }
        if self.save:
            self.eval_results = []

    def record(self, split='val'):
        # record
        for k, v in self.eval_dict.items():
            if k == "answer_top10":
                continue
            if 'type' in k:
                self.eval_dict[k] = sum(v) / self.type_count['type' + k[4] + '_count']
            elif 'non_color' not in k:
                self.eval_dict[k] = sum(v) / self.total_count
                
                print(k, 'overall', sum(v), self.total_count)
            elif 'non_color' in k:
                self.eval_dict[k] = sum(v) / self.non_color_total_count
                print(k, 'non_color', sum(v), self.non_color_total_count)

        if self.eval_dict["target_metric"] > self.best_result:
            is_best = True
            self.best_result = self.eval_dict["target_metric"]
        else:
            is_best = False

        if self.save and (is_best or split == 'test'):
            torch.save(self.eval_results, str(self.save_dir / 'results.pt'))

        return is_best, self.eval_dict