File size: 7,439 Bytes
4e326fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
188
189
190
191
192
193
194
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 "
    "context $source_context to $target_context. "
    "Selected classes: $selected_classes"
)
_REPO = "https://huggingface.co/datasets/dgcnz/pcbm-metashift/resolve/main"
_IMAGES_DIR = Path("data")


class PCBMMetashiftConfig(datasets.BuilderConfig):
    """Builder Config for Food-101"""

    def __init__(
        self,
        metadata_path: str,
        selected_classes: list[str],
        spurious_class: str,
        source_context: str,
        target_context: str,
        **kwargs,
    ):
        """BuilderConfig for Food-101.
        Args:
          data_url: `string`, url to download the zip file from.
          metadata_urls: dictionary with keys 'train' and 'validation' containing the archive metadata URLs
          **kwargs: keyword arguments forwarded to super.
        """
        super(PCBMMetashiftConfig, 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
        self.target_context = target_context


class PCBMMetashift(datasets.GeneratorBasedBuilder):
    """Food-101 Images dataset"""

    BUILDER_CONFIGS = [
        PCBMMetashiftConfig(
            name="task_abcck_bed_cat_dog",
            description="Task 1: bed(cat) -> bed(dog)",
            metadata_path="configs/task_abcck_bed_cat_dog.json",
            selected_classes=["airplane", "bed", "car", "cow", "keyboard"],
            spurious_class="bed",
            source_context="cat",
            target_context="dog",
        ),
        PCBMMetashiftConfig(
            name="task_abcck_bed_dog_cat",
            description="Task 1: bed(dog) -> bed(cat)",
            metadata_path="configs/task_abcck_bed_dog_cat.json",
            selected_classes=["airplane", "bed", "car", "cow", "keyboard"],
            spurious_class="bed",
            source_context="dog",
            target_context="cat",
        ),
        PCBMMetashiftConfig(
            name="task_abcck_car_cat_dog",
            description="Task 1: car(cat) -> car(dog)",
            metadata_path="configs/task_abcck_car_cat_dog.json",
            selected_classes=["airplane", "bed", "car", "cow", "keyboard"],
            spurious_class="car",
            source_context="cat",
            target_context="dog",
        ),
        PCBMMetashiftConfig(
            name="task_abcck_car_dog_cat",
            description="Task 1: car(dog) -> car(cat)",
            metadata_path="configs/task_abcck_car_dog_cat.json",
            selected_classes=["airplane", "bed", "car", "cow", "keyboard"],
            spurious_class="car",
            source_context="dog",
            target_context="cat",
        ),
        PCBMMetashiftConfig(
            name="task_bcmst_table_books_cat",
            description="Task 2: table(books) -> table(cat)",
            metadata_path="configs/task_bcmst_table_books_cat.json",
            selected_classes=["beach", "computer", "motorcycle", "stove", "table"],
            spurious_class="table",
            source_context="books",
            target_context="cat",
        ),
        PCBMMetashiftConfig(
            name="task_bcmst_table_books_dog",
            description="Task 2: table(books) -> table(dog)",
            metadata_path="configs/task_bcmst_table_books_dog.json",
            selected_classes=["beach", "computer", "motorcycle", "stove", "table"],
            spurious_class="table",
            source_context="books",
            target_context="dog",
        ),
        PCBMMetashiftConfig(
            name="task_bcmst_table_cat_dog",
            description="Task 2: table(cat) -> table(dog)",
            metadata_path="configs/task_bcmst_table_cat_dog.json",
            selected_classes=["beach", "computer", "motorcycle", "stove", "table"],
            spurious_class="table",
            source_context="cat",
            target_context="dog",
        ),
        PCBMMetashiftConfig(
            name="task_bcmst_table_dog_cat",
            description="Task 2: table(dog) -> table(cat)",
            metadata_path="configs/task_bcmst_table_dog_cat.json",
            selected_classes=["beach", "computer", "motorcycle", "stove", "table"],
            spurious_class="table",
            source_context="dog",
            target_context="cat",
        ),
    ]

    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,
                target_context=self.config.target_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}/{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,
                }