File size: 5,791 Bytes
2ba8564
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import datasets
import numpy as np
from PIL import Image

_DSPRITES_URL = "https://github.com/google-deepmind/dsprites-dataset/raw/refs/heads/master/dsprites_ndarray_co1sh3sc6or40x32y32_64x64.npz"
_SCREAM_URL = "https://huggingface.co/datasets/randall-lab/dsprites-scream/resolve/main/scream.jpg"

class DSprites(datasets.GeneratorBasedBuilder):
    """Scream dSprites dataset: 3x6x40x32x32 factor combinations, 64x64 RGB images with Scream background."""

    VERSION = datasets.Version("1.0.0")

    def _info(self):
        return datasets.DatasetInfo(
            description=(
                "Scream dSprites dataset: procedurally generated 2D shapes dataset with known ground-truth factors, "
                "commonly used for disentangled representation learning. "
                "This is the ScreamDSprites variant, where each object is embedded onto a random Scream image patch "
                "with the object pixels inverted. "
                "Factors: color (1), shape (3), scale (6), orientation (40), position X (32), position Y (32). "
                "Images are 64x64 RGB."
            ),
            features=datasets.Features(
                {
                    "image": datasets.Image(),  # (64, 64), RGB
                    "index": datasets.Value("int32"),  # index of the image
                    "label": datasets.Sequence(datasets.Value("int32")),  # 6 factor indices (classes)
                    "label_values": datasets.Sequence(datasets.Value("float32")),  # 6 factor continuous values
                    "color": datasets.Value("int32"),  # color index (always 0)
                    "shape": datasets.Value("int32"),  # shape index (0-2)
                    "scale": datasets.Value("int32"),  # scale index (0-5)
                    "orientation": datasets.Value("int32"),  # orientation index (0-39)
                    "posX": datasets.Value("int32"),  # posX index (0-31)
                    "posY": datasets.Value("int32"),  # posY index (0-31)
                    "colorValue": datasets.Value("float64"),  # color index (always 0)
                    "shapeValue": datasets.Value("float64"),  # shape index (0-2)
                    "scaleValue": datasets.Value("float64"),  # scale index (0-5)
                    "orientationValue": datasets.Value("float64"),  # orientation index (0-39)
                    "posXValue": datasets.Value("float64"),  # posX index (0-31)
                    "posYValue": datasets.Value("float64"),  # posY index (0-31)
                }
            ),
            supervised_keys=("image", "label"),
            homepage="https://github.com/google-research/disentanglement_lib/tree/master",
            license="apache-2.0",
            citation="""@inproceedings{locatello2019challenging,
  title={Challenging Common Assumptions in the Unsupervised Learning of Disentangled Representations},
  author={Locatello, Francesco and Bauer, Stefan and Lucic, Mario and Raetsch, Gunnar and Gelly, Sylvain and Sch{\"o}lkopf, Bernhard and Bachem, Olivier},
  booktitle={International Conference on Machine Learning},
  pages={4114--4124},
  year={2019}
}""",
        )

    def _split_generators(self, dl_manager):
        npz_path = dl_manager.download(_DSPRITES_URL)
        scream_path = dl_manager.download_and_extract(_SCREAM_URL)

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={"npz_path": npz_path, "scream_path": scream_path},
            ),
        ]

    def _generate_examples(self, npz_path, scream_path):
        # Load dSprites data
        data = np.load(npz_path, allow_pickle=True)
        images = data["imgs"]  # shape: (737280, 64, 64), uint8
        latents_classes = data["latents_classes"]  # shape: (737280, 6), int64
        latents_values = data["latents_values"]    # shape: (737280, 6), float64

        # Load Scream image once
        scream_img = Image.open(scream_path).convert("RGB")
        scream_img = scream_img.resize((350, 274))
        scream = np.array(scream_img).astype(np.float32) / 255.0  # (H, W, 3)

        # Iterate over images
        for idx in range(len(images)):
            img = images[idx].astype(np.float32)  # (64, 64), float32

            # Random scream patch
            x_crop = np.random.randint(0, scream.shape[0] - 64)
            y_crop = np.random.randint(0, scream.shape[1] - 64)
            background_patch = scream[x_crop:x_crop + 64, y_crop:y_crop + 64]  # (64, 64, 3)

            # Create mask
            mask = img == 1
            mask = mask[..., None]  # (64, 64, 1)

            # Invert object region
            output_img = np.copy(background_patch)
            output_img[mask.squeeze()] = 1.0 - background_patch[mask.squeeze()]

            # Convert to RGB PIL
            img_pil = Image.fromarray((output_img * 255).astype(np.uint8), mode="RGB")

            # Labels
            factors_classes = latents_classes[idx].tolist()
            factors_values = latents_values[idx].tolist()

            yield idx, {
                "image": img_pil,
                "index": idx,
                "label": factors_classes,
                "label_values": factors_values,
                "color": factors_classes[0],
                "shape": factors_classes[1],
                "scale": factors_classes[2],
                "orientation": factors_classes[3],
                "posX": factors_classes[4],
                "posY": factors_classes[5],
                "colorValue": factors_values[0],
                "shapeValue": factors_values[1],
                "scaleValue": factors_values[2],
                "orientationValue": factors_values[3],
                "posXValue": factors_values[4],
                "posYValue": factors_values[5],
            }