mweiss commited on
Commit
6aae17c
1 Parent(s): 164bee7

Create fashion_mnist_ambiguous.py

Browse files
Files changed (1) hide show
  1. fashion_mnist_ambiguous.py +163 -0
fashion_mnist_ambiguous.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """An ambiguous fashion mnist data set"""
2
+
3
+ import csv
4
+
5
+ import datasets
6
+ import numpy as np
7
+ from datasets.tasks import ImageClassification
8
+
9
+ _CITATION = """\
10
+ @misc{https://doi.org/10.48550/arxiv.2207.10495,
11
+ doi = {10.48550/ARXIV.2207.10495},
12
+ url = {https://arxiv.org/abs/2207.10495},
13
+ author = {Weiss, Michael and Gómez, André García and Tonella, Paolo},
14
+ title = {A Forgotten Danger in DNN Supervision Testing: Generating and Detecting True Ambiguity},
15
+ publisher = {arXiv},
16
+ year = {2022}
17
+ }
18
+ """
19
+
20
+ _DESCRIPTION = """\
21
+ The images were created such that they have an unclear ground truth,
22
+ i.e., such that they are similar to multiple - but not all - of the datasets classes.
23
+ Robust and uncertainty-aware models should be able to detect and flag these ambiguous images.
24
+ As such, the dataset should be merged / mixed with the original dataset and we
25
+ provide such 'mixed' splits for convenience. Please refer to the dataset card for details.
26
+ """
27
+
28
+ _HOMEPAGE = "https://github.com/testingautomated-usi/ambiguous-datasets"
29
+ _LICENSE = "https://raw.githubusercontent.com/testingautomated-usi/ambiguous-datasets/main/LICENSE"
30
+
31
+ _VERSION = "0.1.0"
32
+ _URL = f"https://github.com/testingautomated-usi/ambiguous-datasets/releases/download/v{_VERSION}/"
33
+
34
+ _URLS = {
35
+ "train": "fmnist-test.csv",
36
+ "test": "fmnist-test.csv",
37
+ }
38
+
39
+ _NAMES = [
40
+ "T - shirt / top",
41
+ "Trouser",
42
+ "Pullover",
43
+ "Dress",
44
+ "Coat",
45
+ "Sandal",
46
+ "Shirt",
47
+ "Sneaker",
48
+ "Bag",
49
+ "Ankle boot",
50
+ ]
51
+
52
+
53
+ class FashionMnistAmbiguous(datasets.GeneratorBasedBuilder):
54
+ """An ambiguous fashion mnist data set"""
55
+
56
+ BUILDER_CONFIGS = [
57
+ datasets.BuilderConfig(
58
+ name="fashion_mnist_ambiguous",
59
+ version=datasets.Version(_VERSION),
60
+ description=_DESCRIPTION,
61
+ )
62
+ ]
63
+
64
+ def _info(self):
65
+ return datasets.DatasetInfo(
66
+ description=_DESCRIPTION,
67
+ features=datasets.Features(
68
+ {
69
+ "image": datasets.Image(),
70
+ "label": datasets.features.ClassLabel(names=_NAMES),
71
+ "text_label": datasets.Value("string"),
72
+ "p_label": datasets.Sequence(datasets.Value("float32"), length=10),
73
+ "is_ambiguous": datasets.Value("bool"),
74
+ }
75
+ ),
76
+ supervised_keys=("image", "label"),
77
+ homepage=_HOMEPAGE,
78
+ citation=_CITATION,
79
+ task_templates=[ImageClassification(image_column="image", label_column="label")],
80
+ )
81
+
82
+ def _split_generators(self, dl_manager):
83
+ urls_to_download = {key: _URL + fname for key, fname in _URLS.items()}
84
+ downloaded_files = dl_manager.download(urls_to_download)
85
+
86
+ return [
87
+ datasets.SplitGenerator(
88
+ name=datasets.Split.TRAIN,
89
+ gen_kwargs={
90
+ "filepath": downloaded_files["train"],
91
+ "split": "train",
92
+ },
93
+ ),
94
+ datasets.SplitGenerator(
95
+ name=datasets.Split.TEST,
96
+ gen_kwargs={
97
+ "filepath": downloaded_files["test"],
98
+ "split": "test",
99
+ },
100
+ ),
101
+ datasets.SplitGenerator(
102
+ name="train_mixed",
103
+ gen_kwargs={
104
+ "filepath": downloaded_files["train"],
105
+ "split": "train_mixed",
106
+ },
107
+ ),
108
+ datasets.SplitGenerator(
109
+ name="test_mixed",
110
+ gen_kwargs={
111
+ "filepath": downloaded_files["test"],
112
+ "split": "test_mixed",
113
+ },
114
+ ),
115
+ ]
116
+
117
+ def _generate_examples(self, filepath, split):
118
+ """This function returns the examples in the raw form."""
119
+
120
+ def _gen_amb_images():
121
+ with open(filepath) as csvfile:
122
+ spamreader = csv.reader(csvfile, delimiter=',', quotechar='"')
123
+ for i, row in enumerate(spamreader):
124
+ if i == 0:
125
+ continue
126
+
127
+ det_label = int(row[7])
128
+ class_1, class_2 = int(row[3]), int(row[4])
129
+ p_1, p_2 = float(row[5]), float(row[6])
130
+ text_label = f"p({_NAMES[class_1]})={p_1:.2f}, p({_NAMES[class_2]})={p_2:.2f}"
131
+
132
+ p_label = [0.0] * 10
133
+ p_label[class_1] = p_1
134
+ p_label[class_2] = p_2
135
+
136
+ image = np.array(row[9:], dtype=np.uint8).reshape(28, 28)
137
+
138
+ yield i, {"image": image, "label": det_label,
139
+ "text_label": text_label, "p_label": p_label, "is_ambiguous": True}
140
+
141
+ if split == "test" or split == "train":
142
+ yield from _gen_amb_images()
143
+
144
+ elif split == "test_mixed" or split == "train_mixed":
145
+
146
+ nominal_samples = []
147
+ nom_split = "test" if split == "test_mixed" else "train"
148
+ nominal_dataset = datasets.load_dataset("fashion_mnist", split=nom_split)
149
+ for x in nominal_dataset:
150
+ nominal_samples.append({
151
+ "image": np.array(x["image"]),
152
+ "label": x["label"],
153
+ "text_label": f"p({_NAMES[x['label']]})=1",
154
+ "p_label": [1.0 if i == x["label"] else 0.0 for i in range(10)],
155
+ "is_ambiguous": False
156
+ })
157
+
158
+ ambiguous_samples = list([x for i, x in _gen_amb_images()])
159
+ all_samples = nominal_samples + ambiguous_samples
160
+ np.random.RandomState(42).shuffle(all_samples)
161
+
162
+ for i, x in enumerate(all_samples):
163
+ yield i, x