Fraser Greenlee commited on
Commit
b96962a
·
1 Parent(s): 2a4ee76

add script

Browse files
Files changed (1) hide show
  1. mnist-text-default.py +185 -0
mnist-text-default.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ """MNIST text dataset."""
3
+
4
+ from __future__ import absolute_import, division, print_function
5
+
6
+ import json
7
+ import os
8
+ import math
9
+
10
+ import numpy as np
11
+ import datasets
12
+
13
+
14
+ _DESCRIPTION = """\
15
+ MNIST dataset adapted to a text-based representation.
16
+
17
+ This allows testing interpolation quality for Transformer-VAEs.
18
+
19
+ System is heavily inspired by Matthew Rayfield's work https://youtu.be/Z9K3cwSL6uM
20
+
21
+ Works by quantising each MNIST pixel into one of 64 characters.
22
+ Every sample has an up & down version to encourage the model to learn rotation invarient features.
23
+
24
+ Use `.array_to_text(` and `.text_to_array(` methods to test your generated data.
25
+
26
+ Data format:
27
+ - text: (30 x 28 tokens, 840 tokens total): Textual representation of MNIST digit, for example:
28
+ ```
29
+ 00 down ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
30
+ 01 down ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
31
+ 02 down ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
32
+ 03 down ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
33
+ 04 down ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
34
+ 05 down ! ! ! ! ! ! ! ! ! ! ! ! ! % % % @ C L ' J a ^ @ ! ! ! !
35
+ 06 down ! ! ! ! ! ! ! ! ( * 8 G K ` ` ` ` ` Y L ` ] Q 1 ! ! ! !
36
+ 07 down ! ! ! ! ! ! ! - \ ` ` ` ` ` ` ` ` _ 8 5 5 / * ! ! ! ! !
37
+ 08 down ! ! ! ! ! ! ! % W ` ` ` ` ` R N ^ ] ! ! ! ! ! ! ! ! ! !
38
+ 09 down ! ! ! ! ! ! ! ! 5 H ; ` ` T # ! + G ! ! ! ! ! ! ! ! ! !
39
+ 10 down ! ! ! ! ! ! ! ! ! $ ! G ` 7 ! ! ! ! ! ! ! ! ! ! ! ! ! !
40
+ 11 down ! ! ! ! ! ! ! ! ! ! ! C ` P ! ! ! ! ! ! ! ! ! ! ! ! ! !
41
+ 12 down ! ! ! ! ! ! ! ! ! ! ! # P ` 2 ! ! ! ! ! ! ! ! ! ! ! ! !
42
+ 13 down ! ! ! ! ! ! ! ! ! ! ! ! ) ] Y I < ! ! ! ! ! ! ! ! ! ! !
43
+ 14 down ! ! ! ! ! ! ! ! ! ! ! ! ! 5 ] ` ` > ' ! ! ! ! ! ! ! ! !
44
+ 15 down ! ! ! ! ! ! ! ! ! ! ! ! ! ! , O ` ` F ' ! ! ! ! ! ! ! !
45
+ 16 down ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! % 8 ` ` O ! ! ! ! ! ! ! !
46
+ 17 down ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! _ ` _ 1 ! ! ! ! ! ! !
47
+ 18 down ! ! ! ! ! ! ! ! ! ! ! ! ! ! , A N ` ` T ! ! ! ! ! ! ! !
48
+ 19 down ! ! ! ! ! ! ! ! ! ! ! ! * F Z ` ` ` _ N ! ! ! ! ! ! ! !
49
+ 20 down ! ! ! ! ! ! ! ! ! ! ' = X ` ` ` ` S 4 ! ! ! ! ! ! ! ! !
50
+ 21 down ! ! ! ! ! ! ! ! & 1 V ` ` ` ` R 5 ! ! ! ! ! ! ! ! ! ! !
51
+ 22 down ! ! ! ! ! ! % K W ` ` ` ` Q 5 # ! ! ! ! ! ! ! ! ! ! ! !
52
+ 23 down ! ! ! ! . L Y ` ` ` ` ^ B # ! ! ! ! ! ! ! ! ! ! ! ! ! !
53
+ 24 down ! ! ! ! C ` ` ` V B B % ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
54
+ 25 down ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
55
+ 26 down ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
56
+ 27 down ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
57
+ ```
58
+ - label: Just a number with the texts matching label.
59
+
60
+ """
61
+
62
+ _CITATION = """\
63
+ @dataset{dataset,
64
+ author = {Fraser Greenlee},
65
+ year = {2021},
66
+ month = {1},
67
+ pages = {},
68
+ title = {MNIST text dataset.},
69
+ doi = {}
70
+ }
71
+ """
72
+
73
+ _TRAIN_DOWNLOAD_URL = "https://raw.githubusercontent.com/Fraser-Greenlee/my-huggingface-datasets/master/data/mnist-text/train.json.zip"
74
+ _TEST_DOWNLOAD_URL = "https://raw.githubusercontent.com/Fraser-Greenlee/my-huggingface-datasets/master/data/mnist-text/test.json"
75
+
76
+ LABELS = list(range(10))
77
+ CUSTOM_METHODS = ['array_to_text', 'text_to_array']
78
+
79
+ IMG_SIZE = (30, 28)
80
+
81
+
82
+ class MnistText(datasets.GeneratorBasedBuilder):
83
+ """MNIST represented by text."""
84
+
85
+ def as_dataset(self, *args, **kwargs):
86
+ f"""
87
+ Return a Dataset for the specified split.
88
+
89
+ Modified to add custom methods {CUSTOM_METHODS} to the dataset.
90
+ This allows rendering the text as images & vice versa.
91
+ """
92
+ a_dataset = super().as_dataset(*args, **kwargs)
93
+ for method in CUSTOM_METHODS:
94
+ setattr(a_dataset, f'custom_{method}', getattr(self, method))
95
+ return a_dataset
96
+
97
+ @staticmethod
98
+ def array_to_text(pixels: np.array):
99
+ '''
100
+ Takes a 2D array of pixel brightnesses and converts them to text.
101
+ Uses 64 tokens to represent all brightness values.
102
+ '''
103
+ width = pixels.shape[0]
104
+ height = pixels.shape[1]
105
+
106
+ lines = []
107
+
108
+ for y in range(height):
109
+ split = ['%02d down' % y]
110
+
111
+ for x in range(width):
112
+ brightness = pixels[y, x]
113
+
114
+ mBrightness = math.floor(brightness * 64)
115
+ s = chr(mBrightness + 33)
116
+
117
+ split.append(s)
118
+
119
+ lines.append(' '.join(split))
120
+
121
+ reversed = []
122
+ for line in lines:
123
+ reversed.insert(0, (line.replace(' down ', ' up ', 1)))
124
+
125
+ return ['\n'.join(lines), '\n'.join(reversed)]
126
+
127
+ @staticmethod
128
+ def text_to_array(text: str):
129
+ '''
130
+ Takes a text sequences and tries to convert it into a 2D numpy array of brightnesses.
131
+ If parts of the text don't match the format they will be skipped.
132
+ '''
133
+ lines = text.strip().split('\n')
134
+ pixels = np.zeros((IMG_SIZE[1], IMG_SIZE[0] - 2))
135
+ tokens = None
136
+ for y in range(min(IMG_SIZE[1], len(lines))):
137
+ line = lines[y].strip()
138
+ tokens = line.split(' ')
139
+ for i in range(2, min(IMG_SIZE[0], len(tokens))):
140
+ token = tokens[i]
141
+ if len(token) == 1:
142
+ tkn_v = (ord(token) - 33)
143
+ if tkn_v >= 0 and tkn_v <= 64:
144
+ pixels[y, i - 2] = tkn_v / 64
145
+
146
+ if not lines:
147
+ return pixels
148
+
149
+ if tokens and len(tokens) > 1 and tokens[1] == 'up':
150
+ pixels = pixels[::-1]
151
+
152
+ return pixels
153
+
154
+ def _info(self):
155
+ return datasets.DatasetInfo(
156
+ description=_DESCRIPTION,
157
+ features=datasets.Features(
158
+ {
159
+ 'label': datasets.features.ClassLabel(names=LABELS),
160
+ 'text': datasets.Value("string"),
161
+ }
162
+ ),
163
+ homepage="https://github.com/Fraser-Greenlee/my-huggingface-datasets",
164
+ citation=_CITATION,
165
+ )
166
+
167
+ def _split_generators(self, dl_manager):
168
+ train_path = dl_manager.download_and_extract(_TRAIN_DOWNLOAD_URL)
169
+ test_path = dl_manager.download_and_extract(_TEST_DOWNLOAD_URL)
170
+ return [
171
+ datasets.SplitGenerator(
172
+ name=datasets.Split.TRAIN, gen_kwargs={"filepath": os.path.join(train_path, 'train.json')}
173
+ ),
174
+ datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepath": test_path}),
175
+ ]
176
+
177
+ def _generate_examples(self, filepath):
178
+ """Generate examples."""
179
+ with open(filepath, encoding="utf-8") as json_lines_file:
180
+ data = []
181
+ for line in json_lines_file:
182
+ data.append(json.loads(line))
183
+
184
+ for id_, row in enumerate(data):
185
+ yield id_, row