-
Notifications
You must be signed in to change notification settings - Fork 2
/
cdatasets.py
174 lines (129 loc) · 5.48 KB
/
cdatasets.py
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
"""
Datasets used in our experiments on (cloned) CIFAR10/100.
Author : Sebastian Goldt <[email protected]>
Date : August 2022
Version : 0.1
"""
import os
from typing import Any, Callable, Optional, Tuple
import numpy as np
from PIL import Image
import torch
from torchvision.datasets import CIFAR10, VisionDataset
# Code to create Gaussian clones
import censoring
class ClonedCIFAR(VisionDataset):
"""
Dataset interface for a cloned version of CIFAR10/100, usually obtained using a
combination of generative model + classifier.
The code is based on the CIFAR10 implementation of pyTorch:
https://pytorch.org/vision/stable/_modules/torchvision/datasets/cifar.html#CIFAR10
The CIFAR100 class is just a subclass of that class that redefines some constants.
Args:
root (string): Root directory of dataset where files exist
train (bool, optional): If True, creates dataset from training set, otherwise
creates from test set.
transform (callable, optional): A function/transform that takes in an PIL image
and returns a transformed version. E.g, ``transforms.RandomCrop``
target_transform (callable, optional): A function/transform that takes in the
target and transforms it.
"""
def __init__(
self,
root: str,
name: str,
train: bool = True,
transform: Optional[Callable] = None,
target_transform: Optional[Callable] = None,
download: bool = False,
) -> None:
super().__init__(root, transform=transform, target_transform=target_transform)
self.train = train # training set or test set
mode = "train" if self.train else "test"
self.data = np.load(os.path.join(root, f"{name}_{mode}_xs.npy"))
self.targets = np.load(os.path.join(root, f"{name}_{mode}_ys.npy"))
def __getitem__(self, index: int) -> Tuple[Any, Any]:
"""
Args:
index (int): Index
Returns:
tuple: (image, target) where target is index of the target class.
"""
img, target = self.data[index], self.targets[index]
# doing this so that it is consistent with all other datasets
# to return a PIL Image
img = Image.fromarray(img)
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
return img, target
def __len__(self) -> int:
return len(self.data)
def extra_repr(self) -> str:
split = "Train" if self.train is True else "Test"
return f"Split: {split}"
class GaussianCIFAR(VisionDataset):
"""
Dataset interface for a Gaussian clone of CIFAR10/100, using the censoring library.
The code is based on the CIFAR10 implementation of pyTorch:
https://pytorch.org/vision/stable/_modules/torchvision/datasets/cifar.html#CIFAR10
Args:
cifar_dataset (CIFAR10/CIFAR100): loaded CIFAR10/100 dataset
isotropic (bool, optional) : if True, covariances of the Gaussians are isotropic.
train (bool, optional): If True, creates dataset from training set, otherwise
creates from test set.
transform (callable, optional): A function/transform that takes in an PIL image
and returns a transformed version. E.g, ``transforms.RandomCrop``
target_transform (callable, optional): A function/transform that takes in the
target and transforms it.
"""
def __init__(
self,
cifar_dataset: CIFAR10, # CIFAR100 is a subclass of CIFAR100
isotropic: bool = False,
train: bool = True,
transform: Optional[Callable] = None,
target_transform: Optional[Callable] = None,
download: bool = False,
) -> None:
super().__init__(None, transform=transform, target_transform=target_transform)
if cifar_dataset.train != train:
raise ValueError("mismatch between CIFAR data set given and train flag")
self.train = train # training set or test set
# extract inputs, labels
cifar_xs = torch.tensor(cifar_dataset.data).float()
cifar_ys = torch.tensor(cifar_dataset.targets)
# create clone
clone_xs, clone_ys = censoring.censor2d(
cifar_xs, cifar_ys, isotropic=isotropic
)
self.targets = clone_ys.numpy()
# clamp the inputs to have the right range
clone_xs = torch.clamp(clone_xs, min=0, max=255)
# transform to numpy and...
clone_xs = np.round(clone_xs.numpy())
# ...match datatype of CIFAR
clone_xs = np.array(clone_xs, dtype=cifar_dataset.data.dtype)
self.data = clone_xs
def __getitem__(self, index: int) -> Tuple[Any, Any]:
"""
Args:
index (int): Index
Returns:
tuple: (image, target) where target is index of the target class.
"""
img, target = self.data[index], self.targets[index]
# doing this so that it is consistent with all other datasets
# to return a PIL Image
img = Image.fromarray(img)
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
return img, target
def __len__(self) -> int:
return len(self.data)
def extra_repr(self) -> str:
split = "Train" if self.train is True else "Test"
return f"Split: {split}"