|
"""Create a hard multiple choice subset of the ImageNet validation split based on human accuracy annotation data.""" |
|
|
|
from typing import Dict |
|
import argparse |
|
import json |
|
import pickle |
|
import numpy as np |
|
import scipy.io |
|
|
|
|
|
def get_imagenet_labels() -> Dict[str, str]: |
|
"""Return ground truth wnids.""" |
|
with open("ILSVRC2012_devkit_t12/data/ILSVRC2012_validation_ground_truth.txt") as fp: |
|
ilsvrc_idxs = [int(line.strip()) for line in fp] |
|
ilsvrc_metadata = scipy.io.loadmat("ILSVRC2012_devkit_t12/data/meta.mat", simplify_cells=True) |
|
ilsvrc_idx2wnid = { |
|
synset['ILSVRC2012_ID']: synset['WNID'] |
|
for synset in ilsvrc_metadata['synsets'] |
|
} |
|
return { |
|
f"ILSVRC2012_val_{img_id:0>8}.JPEG": ilsvrc_idx2wnid[idx] |
|
for img_id, idx in enumerate(ilsvrc_idxs, start=1) |
|
} |
|
|
|
|
|
def get_close_examples(num_choices: int = 4, seed: int | np.random.Generator = None): |
|
""" |
|
Construct easy MCQA examples using ImageNet hierarchy. |
|
""" |
|
rng = np.random.default_rng(seed) |
|
with open("imagenet_wnids.txt") as fp: |
|
wnids = [line.strip() for line in fp] |
|
gt_labels = get_imagenet_labels() |
|
|
|
with open("human_accuracy_annotations.pkl", "rb") as fp: |
|
annotation_data = pickle.load(fp) |
|
examples = [] |
|
for imgname, annot in annotation_data['initial_annots'].items(): |
|
if imgname.startswith("ILSVRC2012"): |
|
if gt_labels[imgname] not in annot.get('wrong', []): |
|
|
|
other_choices = list(set(wnids) - {gt_labels[imgname]}) |
|
wrong_choices = list(rng.choice(other_choices, size=num_choices - 1, replace=False)) |
|
examples.append({ |
|
'image': imgname, |
|
'choices': [gt_labels[imgname]] + list(wrong_choices), |
|
'correct_answer': gt_labels[imgname] |
|
}) |
|
return examples |
|
|
|
|
|
if __name__ == "__main__": |
|
parser = argparse.ArgumentParser() |
|
parser.add_argument("--n-choices", "-n", type=int, required=True) |
|
parser.add_argument("--output", "-o", type=str, default=None) |
|
parser.add_argument("--seed", type=int, default=42) |
|
args = parser.parse_args() |
|
dataset = get_close_examples(args.n_choices, seed=args.seed) |
|
print(f"No. of examples: {len(dataset)}") |
|
if args.output: |
|
with open(args.output, "w") as fp: |
|
json.dump(dataset, fp, indent=2) |
|
print(f"Saved to '{args.output}'") |
|
|