echarlaix HF staff commited on
Commit
46e8818
1 Parent(s): 28683f7

Add vqa dataset script

Browse files
Files changed (1) hide show
  1. vqa-lxmert.py +158 -0
vqa-lxmert.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """The Visual Question Answering (VQA) dataset preprocessed for LXMERT."""
16
+
17
+ import base64
18
+ import csv
19
+ import json
20
+ import os
21
+ import sys
22
+
23
+ import datasets
24
+ import numpy as np
25
+
26
+
27
+ csv.field_size_limit(sys.maxsize)
28
+
29
+
30
+ _CITATION = """\
31
+ @inproceedings{antol2015vqa,
32
+ title={Vqa: Visual question answering},
33
+ author={Antol, Stanislaw and Agrawal, Aishwarya and Lu, Jiasen and Mitchell, Margaret and Batra, Dhruv and Zitnick, C Lawrence and Parikh, Devi},
34
+ booktitle={Proceedings of the IEEE international conference on computer vision},
35
+ pages={2425--2433},
36
+ year={2015}
37
+ }
38
+ """
39
+
40
+ _DESCRIPTION = """\
41
+ VQA is a new dataset containing open-ended questions about images.
42
+ These questions require an understanding of vision, language and commonsense knowledge to answer.
43
+ """
44
+
45
+ _URLS = {
46
+ "train": "https://nlp.cs.unc.edu/data/lxmert_data/vqa/train.json",
47
+ "train_feat": "https://nlp.cs.unc.edu/data/lxmert_data/mscoco_imgfeat/train2014_obj36.zip",
48
+ "dev": "https://nlp.cs.unc.edu/data/lxmert_data/vqa/valid.json",
49
+ "dev_feat": "https://nlp.cs.unc.edu/data/lxmert_data/mscoco_imgfeat/val2014_obj36.zip",
50
+ "ans2label": "https://raw.githubusercontent.com/airsplay/lxmert/master/data/vqa/trainval_ans2label.json",
51
+ }
52
+
53
+ _TRAIN_IMG_PATH = "train2014_obj36.tsv"
54
+ _DEV_IMG_PATH = "mscoco_imgfeat/val2014_obj36.tsv"
55
+
56
+ FIELDNAMES = [
57
+ "img_id", "img_h", "img_w", "objects_id", "objects_conf", "attrs_id", "attrs_conf", "num_boxes", "boxes", "features"
58
+ ]
59
+
60
+ _SHAPE_FEATURES = (36, 2048)
61
+ _SHAPE_BOXES = (36, 4)
62
+
63
+
64
+ class VqaV2Lxmert(datasets.GeneratorBasedBuilder):
65
+ """The VQAv2.0 dataset preprocessed for LXMERT, with the objects features detected by a Faster RCNN replacing the
66
+ raw images."""
67
+
68
+ BUILDER_CONFIGS = [
69
+ datasets.BuilderConfig(name="vqa", version=datasets.Version("2.0.0"), description="VQA version 2 dataset."),
70
+ ]
71
+
72
+ def _info(self):
73
+ features = datasets.Features(
74
+ {
75
+ "question": datasets.Value("string"),
76
+ "question_type": datasets.Value("string"),
77
+ "question_id": datasets.Value("int32"),
78
+ "image_id": datasets.Value("string"),
79
+ "features": datasets.Array2D(_SHAPE_FEATURES, dtype="float32"),
80
+ "boxes": datasets.Array2D(_SHAPE_BOXES, dtype="float32"),
81
+ "answer_type": datasets.Value("string"),
82
+ "label": datasets.Sequence(
83
+ {
84
+ "ids": datasets.Value("int32"),
85
+ "weights": datasets.Value("float32"),
86
+ }
87
+ ),
88
+ }
89
+ )
90
+ return datasets.DatasetInfo(
91
+ description=_DESCRIPTION,
92
+ features=features,
93
+ supervised_keys=None,
94
+ citation=_CITATION,
95
+ )
96
+
97
+ def _split_generators(self, dl_manager):
98
+ """Returns SplitGenerators."""
99
+ dl_dir = dl_manager.download_and_extract(_URLS)
100
+ self.ans2label = json.load(open(dl_dir["ans2label"]))
101
+
102
+ return [
103
+ datasets.SplitGenerator(
104
+ name=datasets.Split.TRAIN,
105
+ gen_kwargs={"filepath": dl_dir["train"], "imgfeat": os.path.join(dl_dir["train_feat"], _TRAIN_IMG_PATH)},
106
+ ),
107
+ datasets.SplitGenerator(
108
+ name=datasets.Split.VALIDATION,
109
+ gen_kwargs={"filepath": dl_dir["dev"], "imgfeat": os.path.join(dl_dir["dev_feat"], _DEV_IMG_PATH)},
110
+ ),
111
+ ]
112
+
113
+ def _load_features(self, filepath):
114
+ """Returns a dictionary mapping an image id to the corresponding image's objects features."""
115
+ id2features = {}
116
+ with open(filepath) as f:
117
+ reader = csv.DictReader(f, FIELDNAMES, delimiter="\t")
118
+ for i, item in enumerate(reader):
119
+ features = {}
120
+ for key in ["img_h", "img_w", "num_boxes"]:
121
+ features[key] = int(item[key])
122
+ num_boxes = features["num_boxes"]
123
+ decode_config = [
124
+ ("objects_id", (num_boxes,), np.int64),
125
+ ("objects_conf", (num_boxes,), np.float32),
126
+ ("attrs_id", (num_boxes,), np.int64),
127
+ ("attrs_conf", (num_boxes,), np.float32),
128
+ ("boxes", (num_boxes, 4), np.float32),
129
+ ("features", (num_boxes, -1), np.float32),
130
+ ]
131
+ for key, shape, dtype in decode_config:
132
+ features[key] = np.frombuffer(base64.b64decode(item[key]), dtype=dtype).reshape(shape)
133
+ id2features[item["img_id"]] = features
134
+ return id2features
135
+
136
+ def _generate_examples(self, filepath, imgfeat):
137
+ """ Yields examples as (key, example) tuples."""
138
+ id2features = self._load_features(imgfeat)
139
+ with open(filepath, encoding="utf-8") as f:
140
+ vqa = json.load(f)
141
+ for id_, d in enumerate(vqa):
142
+ img_features = id2features[d["img_id"]]
143
+ ids = [self.ans2label[x] for x in d["label"].keys()]
144
+ weights = list(d["label"].values())
145
+ yield id_, {
146
+ "question": d["sent"],
147
+ "question_type": d["question_type"],
148
+ "question_id": d["question_id"],
149
+ "image_id": d["img_id"],
150
+ "features": img_features["features"],
151
+ "boxes": img_features["boxes"],
152
+ "answer_type": d["answer_type"],
153
+ "label": {
154
+ "ids": ids,
155
+ "weights": weights,
156
+ },
157
+ }
158
+