File size: 7,151 Bytes
83c227c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 datasets
import json
from string import Template
from pathlib import Path

_HOMEPAGE = ""
_CITATION = ""
_LICENSE = ""
_DESCRIPTION_TEMPLATE = Template(
    "$num_classes-way image classification task "
    "to test domain shift of class $spurious_class from "
    "source context $source_context to a target context without $source_context "
    "Selected classes: $selected_classes"
)
_REPO = "https://huggingface.co/datasets/dgcnz/pcbm_survey/resolve/main"


class PCBMSurveyConfig(datasets.BuilderConfig):
    """Builder Config for PCBMSurvey"""

    def __init__(
        self,
        metadata_path: str,
        selected_classes: list[str],
        spurious_class: str,
        source_context: str,
        **kwargs,
    ):
        super(PCBMSurveyConfig, self).__init__(
            version=datasets.Version("1.0.0"), **kwargs
        )
        self.metadata_path = metadata_path
        self.selected_classes = selected_classes
        self.spurious_class = spurious_class
        self.source_context = source_context


class PCBMSurvey(datasets.GeneratorBasedBuilder):
    """PCBM Metashift Survey Images dataset"""

    """
    task_1_bed_dog.json | airplane, bed, car, cow, keyboard |  bed(dog)
    task_2_keyboard_cat.json | beach, bus, airplane, keyboard, bird | keyboard(cat)
    task_3_bed_cat.json | beach, car, airplane, bed, bird | bed(cat) 
    task_4_couch_cat.json | beach, motorcycle, airplane, couch, bird | couch(cat)
    task_5_painting_lamp.json | bus, painting, cat, computer, snowboard | painting(lamp)
    task_6_pillow_clock.json | bus, pillow, cat, computer, snowboard | pillow(clock)
    task_7_television_fireplace.json | bus, television, cat, computer, snowboard | television(fireplace)
    task_8_fork_tomato.json | car, fork, table, bed, computer | fork(tomato) 
    task_9_car_snow.json | dog, car, airplane, couch, bird | car(snow)
    """

    BUILDER_CONFIGS = [
        PCBMSurveyConfig(
            name="task_1_bed_dog",
            metadata_path="task_1_bed_dog.json",
            selected_classes=["airplane", "bed", "car", "cow", "keyboard"],
            spurious_class="bed",
            source_context="dog",
        ),
        PCBMSurveyConfig(
            name="task_2_keyboard_cat",
            metadata_path="task_2_keyboard_cat.json",
            selected_classes=["beach", "bus", "airplane", "keyboard", "bird"],
            spurious_class="keyboard",
            source_context="cat",
        ),
        PCBMSurveyConfig(
            name="task_3_bed_cat",
            metadata_path="task_3_bed_cat.json",
            selected_classes=["beach", "car", "airplane", "bed", "bird"],
            spurious_class="bed",
            source_context="cat",
        ),
        PCBMSurveyConfig(
            name="task_4_couch_cat",
            metadata_path="task_4_couch_cat.json",
            selected_classes=["beach", "motorcycle", "airplane", "couch", "bird"],
            spurious_class="couch",
            source_context="cat",
        ),
        PCBMSurveyConfig(
            name="task_5_painting_lamp",
            metadata_path="task_5_painting_lamp.json",
            selected_classes=["bus", "painting", "cat", "computer", "snowboard"],
            spurious_class="painting",
            source_context="lamp",
        ),
        PCBMSurveyConfig(
            name="task_6_pillow_clock",
            metadata_path="task_6_pillow_clock.json",
            selected_classes=["bus", "pillow", "cat", "computer", "snowboard"],
            spurious_class="pillow",
            source_context="clock",
        ),
        PCBMSurveyConfig(
            name="task_7_television_fireplace",
            metadata_path="task_7_television_fireplace.json",
            selected_classes=["bus", "television", "cat", "computer", "snowboard"],
            spurious_class="television",
            source_context="fireplace",
        ),
        PCBMSurveyConfig(
            name="task_8_fork_tomato",
            metadata_path="task_8_fork_tomato.json",
            selected_classes=["car", "fork", "table", "bed", "computer"],
            spurious_class="fork",
            source_context="tomato",
        ),
        PCBMSurveyConfig(
            name="task_9_car_snow",
            metadata_path="task_9_car_snow.json",
            selected_classes=["dog", "car", "airplane", "couch", "bird"],
            spurious_class="car",
            source_context="snow",
        ),
    ]

    def _info(self):
        return datasets.DatasetInfo(
            description=_DESCRIPTION_TEMPLATE.substitute(
                num_classes=len(self.config.selected_classes),
                spurious_class=self.config.spurious_class,
                source_context=self.config.source_context,
                selected_classes=", ".join(self.config.selected_classes),
            ),
            features=datasets.Features(
                {
                    "image": datasets.Image(),
                    "label": datasets.ClassLabel(names=self.config.selected_classes),
                }
            ),
            supervised_keys=("image", "label"),
            homepage=_HOMEPAGE,
            citation=_CITATION,
            license=_LICENSE,
            task_templates=[
                datasets.ImageClassification(image_column="image", label_column="label")
            ],
        )

    def _split_generators(self, dl_manager):
        archive_path = dl_manager.download(f"{_REPO}/data/images.tar.gz")
        metadata_path = dl_manager.download(f"{_REPO}/scenarios/{self.config.metadata_path}")
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "images": dl_manager.iter_archive(archive_path),
                    "metadata_path": metadata_path,
                    "split": "train",
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={
                    "images": dl_manager.iter_archive(archive_path),
                    "metadata_path": metadata_path,
                    "split": "test",
                },
            ),
        ]

    def _generate_examples(self, images, metadata_path: str, split: str):
        """Generate images and labels for splits."""
        with open(metadata_path, encoding="utf-8") as f:
            metadata = json.load(f)
            split_data = metadata["data_splits"][split]
            ids_to_keep = set()
            for _, ids in split_data.items():
                ids_to_keep.update([Path(id).stem for id in ids])

        files = dict()
        for file_path, file_obj in images:
            image_id = Path(file_path).stem
            if image_id in ids_to_keep:
                files[image_id] = (file_obj.read(), file_path)

        for cls, ids in split_data.items():
            for image_id in ids:
                image_id = Path(image_id).stem
                file_obj, file_path = files[image_id]
                yield f"{cls}_{image_id}", {
                    "image": {"path": file_path, "bytes": file_obj},
                    "label": cls,
                }