forked from eliaswalyba/pytorch-deep-learning-minicourse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sequential_tasks.py
265 lines (219 loc) · 9.54 KB
/
sequential_tasks.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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import numpy as np
import six
def pad_sequences(sequences, maxlen=None, dtype='int32',
padding='pre', truncating='pre', value=0.):
if not hasattr(sequences, '__len__'):
raise ValueError('`sequences` must be iterable.')
lengths = []
for x in sequences:
if not hasattr(x, '__len__'):
raise ValueError('`sequences` must be a list of iterables. '
'Found non-iterable: ' + str(x))
lengths.append(len(x))
num_samples = len(sequences)
if maxlen is None:
maxlen = np.max(lengths)
# take the sample shape from the first non empty sequence
# checking for consistency in the main loop below.
sample_shape = tuple()
for s in sequences:
if len(s) > 0:
sample_shape = np.asarray(s).shape[1:]
break
is_dtype_str = np.issubdtype(dtype, np.str_) or np.issubdtype(dtype, np.unicode_)
if isinstance(value, six.string_types) and dtype != object and not is_dtype_str:
raise ValueError("`dtype` {} is not compatible with `value`'s type: {}\n"
"You should set `dtype=object` for variable length strings."
.format(dtype, type(value)))
x = np.full((num_samples, maxlen) + sample_shape, value, dtype=dtype)
for idx, s in enumerate(sequences):
if not len(s):
continue # empty list/array was found
if truncating == 'pre':
trunc = s[-maxlen:]
elif truncating == 'post':
trunc = s[:maxlen]
else:
raise ValueError('Truncating type "%s" '
'not understood' % truncating)
# check `trunc` has expected shape
trunc = np.asarray(trunc, dtype=dtype)
if trunc.shape[1:] != sample_shape:
raise ValueError('Shape of sample %s of sequence at position %s '
'is different from expected shape %s' %
(trunc.shape[1:], idx, sample_shape))
if padding == 'post':
x[idx, :len(trunc)] = trunc
elif padding == 'pre':
x[idx, -len(trunc):] = trunc
else:
raise ValueError('Padding type "%s" not understood' % padding)
return x
def to_categorical(y, num_classes=None, dtype='float32'):
y = np.array(y, dtype='int')
input_shape = y.shape
if input_shape and input_shape[-1] == 1 and len(input_shape) > 1:
input_shape = tuple(input_shape[:-1])
y = y.ravel()
if not num_classes:
num_classes = np.max(y) + 1
n = y.shape[0]
categorical = np.zeros((n, num_classes), dtype=dtype)
categorical[np.arange(n), y] = 1
output_shape = input_shape + (num_classes,)
categorical = np.reshape(categorical, output_shape)
return categorical
class EchoData():
def __init__(self, series_length=40000, batch_size=32,
echo_step=3, truncated_length=10, seed=None):
self.series_length = series_length
self.truncated_length = truncated_length
self.n_batches = series_length//truncated_length
self.echo_step = echo_step
self.batch_size = batch_size
if seed is not None:
np.random.seed(seed)
self.x_batch = None
self.y_batch = None
self.x_chunks = []
self.y_chunks = []
self.generate_new_series()
self.prepare_batches()
def __getitem__(self, index):
if index == 0:
self.generate_new_series()
self.prepare_batches()
return self.x_chunks[index], self.y_chunks[index]
def __len__(self):
return self.n_batches
def generate_new_series(self):
x = np.random.choice(
2,
size=(self.batch_size, self.series_length),
p=[0.5, 0.5])
y = np.roll(x, self.echo_step, axis=1)
y[:, 0:self.echo_step] = 0
self.x_batch = x
self.y_batch = y
def prepare_batches(self):
x = np.expand_dims(self.x_batch, axis=-1)
y = np.expand_dims(self.y_batch, axis=-1)
self.x_chunks = np.split(x, self.n_batches, axis=1)
self.y_chunks = np.split(y, self.n_batches, axis=1)
class TemporalOrderExp6aSequence():
"""
From Hochreiter&Schmidhuber(1997):
The goal is to classify sequences. Elements and targets are represented locally
(input vectors with only one non-zero bit). The sequence starts with an E, ends
with a B (the "trigger symbol") and otherwise consists of randomly chosen symbols
from the set {a, b, c, d} except for two elements at positions t1 and t2 that are
either X or Y . The sequence length is randomly chosen between 100 and 110, t1 is
randomly chosen between 10 and 20, and t2 is randomly chosen between 50 and 60.
There are 4 sequence classes Q, R, S, U which depend on the temporal order of X and Y.
The rules are:
X, X -> Q,
X, Y -> R,
Y , X -> S,
Y , Y -> U.
"""
def __init__(self, length_range=(100, 111), t1_range=(10, 21), t2_range=(50, 61),
batch_size=32, seed=None):
self.classes = ['Q', 'R', 'S', 'U']
self.n_classes = len(self.classes)
self.relevant_symbols = ['X', 'Y']
self.distraction_symbols = ['a', 'b', 'c', 'd']
self.start_symbol = 'B'
self.end_symbol = 'E'
self.length_range = length_range
self.t1_range = t1_range
self.t2_range = t2_range
self.batch_size = batch_size
if seed is not None:
np.random.seed(seed)
all_symbols = self.relevant_symbols + self.distraction_symbols + \
[self.start_symbol] + [self.end_symbol]
self.n_symbols = len(all_symbols)
self.s_to_idx = {s: n for n, s in enumerate(all_symbols)}
self.idx_to_s = {n: s for n, s in enumerate(all_symbols)}
self.c_to_idx = {c: n for n, c in enumerate(self.classes)}
self.idx_to_c = {n: c for n, c in enumerate(self.classes)}
def generate_pair(self):
length = np.random.randint(self.length_range[0], self.length_range[1])
t1 = np.random.randint(self.t1_range[0], self.t1_range[1])
t2 = np.random.randint(self.t2_range[0], self.t2_range[1])
x = np.random.choice(self.distraction_symbols, length)
x[0] = self.start_symbol
x[-1] = self.end_symbol
y = np.random.choice(self.classes)
if y == 'Q':
x[t1], x[t2] = self.relevant_symbols[0], self.relevant_symbols[0]
elif y == 'R':
x[t1], x[t2] = self.relevant_symbols[0], self.relevant_symbols[1]
elif y == 'S':
x[t1], x[t2] = self.relevant_symbols[1], self.relevant_symbols[0]
else:
x[t1], x[t2] = self.relevant_symbols[1], self.relevant_symbols[1]
return ''.join(x), y
# encoding/decoding single instance version
def encode_x(self, x):
idx_x = [self.s_to_idx[s] for s in x]
return to_categorical(idx_x, num_classes=self.n_symbols)
def encode_y(self, y):
idx_y = self.c_to_idx[y]
return to_categorical(idx_y, num_classes=self.n_classes)
def decode_x(self, x):
x = x[np.sum(x, axis=1) > 0] # remove padding
return ''.join([self.idx_to_s[pos] for pos in np.argmax(x, axis=1)])
def decode_y(self, y):
return self.idx_to_c[np.argmax(y)]
# encoding/decoding batch versions
def encode_x_batch(self, x_batch):
return pad_sequences([self.encode_x(x) for x in x_batch],
maxlen=self.length_range[1])
def encode_y_batch(self, y_batch):
return np.array([self.encode_y(y) for y in y_batch])
def decode_x_batch(self, x_batch):
return [self.decode_x(x) for x in x_batch]
def decode_y_batch(self, y_batch):
return [self.idx_to_c[pos] for pos in np.argmax(y_batch, axis=1)]
def __len__(self):
""" Let's assume 1000 sequences as the size of data. """
return int(1000. / self.batch_size)
def __getitem__(self, index):
batch_x, batch_y = [], []
for _ in range(self.batch_size):
x, y = self.generate_pair()
batch_x.append(x)
batch_y.append(y)
return self.encode_x_batch(batch_x), self.encode_y_batch(batch_y)
class DifficultyLevel:
""" On HARD, settings are identical to the original settings from the '97 paper."""
EASY, NORMAL, MODERATE, HARD, NIGHTMARE = range(5)
@staticmethod
def get_predefined_generator(difficulty_level, batch_size=32, seed=8382):
EASY = TemporalOrderExp6aSequence.DifficultyLevel.EASY
NORMAL = TemporalOrderExp6aSequence.DifficultyLevel.NORMAL
MODERATE = TemporalOrderExp6aSequence.DifficultyLevel.MODERATE
HARD = TemporalOrderExp6aSequence.DifficultyLevel.HARD
if difficulty_level == EASY:
length_range = (7, 9)
t1_range = (1, 3)
t2_range = (4, 6)
elif difficulty_level == NORMAL:
length_range = (30, 41)
t1_range = (2, 6)
t2_range = (20, 28)
elif difficulty_level == MODERATE:
length_range = (60, 81)
t1_range = (10, 21)
t2_range = (45, 55)
elif difficulty_level == HARD:
length_range = (100, 111)
t1_range = (10, 21)
t2_range = (50, 61)
else:
length_range = (300, 501)
t1_range = (10, 81)
t2_range = (250, 291)
return TemporalOrderExp6aSequence(length_range, t1_range, t2_range,
batch_size, seed)