forked from rwth-i6/returnn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StereoDataset.py
393 lines (342 loc) · 14 KB
/
StereoDataset.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
"""
This file contains dataset implementations to have an easy to use
interface for using RETURNN for regression.
Applications are for example speech enhancement or mask estimations
"""
__author__ = 'menne'
import os
import numpy as np
import h5py
from collections import deque
from CachedDataset2 import CachedDataset2
from Dataset import DatasetSeq
from BundleFile import BundleFile
from NormalizationData import NormalizationData
from Log import log
class StereoDataset(CachedDataset2):
"""The purpose of this dataset is to be a base dataset for datasets which
have an easy to use interface for using RETURNN as a regression tool
"""
def __init__(self, **kwargs):
"""constructor"""
super(StereoDataset, self).__init__(**kwargs)
self._seq_index_list = None
@property
def num_seqs(self):
"""returns the number of sequences of the dataset
:rtype: int
"""
if self._num_seqs is not None:
return self._num_seqs
raise NotImplementedError
def _collect_single_seq(self, seq_idx):
"""returns the sequence specified by the index seq_idx
:type seq_idx: int
:rtype: DatasetSeq | None
:returns DatasetSeq or None if seq_idx >= num_seqs.
"""
raise NotImplementedError
def init_seq_order(self, epoch=None, seq_list=None):
"""
:type epoch: int|None
:param epoch: epoch number
:type seq_list: list[str] | None seq_list: In case we want to set a predefined order.
:param seq_list: only None is currently supported
Initialize lists:
self.seq_index # sorted seq idx
"""
super(StereoDataset, self).init_seq_order(epoch=epoch, seq_list=seq_list)
if epoch is None:
self._seq_index_list = range(self.num_seqs)
return True
if seq_list:
raise NotImplementedError('init_seq_order of StereoDataset does not support a predefined seq_list yet.')
else:
seq_index = self.get_seq_order_for_epoch(epoch, self.num_seqs, lambda s: self.get_seq_length(s).get('data', None))
self._seq_index_list = seq_index
if epoch is not None:
# Give some hint to the user in case he is wondering why the cache is reloading.
print >> log.v4, "Reinitialize dataset seq order for epoch %i." % epoch
return True
class StereoHdfDataset(StereoDataset):
"""A stereo dataset which needs an hdf file as input. The hdf file
is supposed to always have group 'inputs' and for the training data it
also needs to contain the group 'outputs'. Each group is supposed to
contain one dataset per sequence. The names of the datasets are supposed
to be consecutive numbers starting at 0.
The datasets are 2D numpy arrays, where dimension 0 is the time axis and
dimension 1 is the feature axis. Therefore dimension 0 of the 'input'
dataset and the respective 'output' dataset need to be the same.
"""
def __init__(self, hdfFile, num_outputs=None, normalizationFile=None,
flag_normalizeInputs=True, flag_normalizeTargets=True,
**kwargs):
"""Constructor
:type hdfFile: str
:param hdfFile: path to the hdf file. if a bundle file is given (*.bundle)
all hdf files listed in the bundle file will be used for
the dataset.
:see: BundleFile.BundleFile
:type num_outputs: int
:param num_outputs: this needs to be set if the stereo data hdf file
only contains 'inputs' data (e.g. for the extraction
process). Only if no 'outputs' data exists in the hdf
file num_outputs is used.
:type normalizationFile: str | None
:param normalizationFile: path to a HDF file with normalization data.
The file is optional: if it is not provided then
no normalization is performed.
:see: NormalizationData.NormalizationData
:type flag_normalizeInputs: bool
:param flag_normalizeInputs: if True then inputs will be normalized
provided that the normalization HDF file has
necessary datasets (i.e. mean and variance)
:type flag_normalizeTargets: bool
:param flag_normalizeTargets: if True then targets will be normalized
provided that the normalization HDF file has
necessary datasets (i.e. mean and variance)
"""
super(StereoHdfDataset, self).__init__(**kwargs)
self._flag_normalizeInputs = flag_normalizeInputs
self._flag_normalizeTargets = flag_normalizeTargets
# properties of the object which will be set further
self.num_inputs = None
self.num_outputs = None
self._filePaths = None
self._fileHandlers = None
self._seqMap = None
self._normData = None
if not os.path.isfile(hdfFile):
raise IOError(hdfFile + ' does not exits')
self._initHdfFileHandlers(hdfFile)
# set number of sequences in the dataset
self._num_seqs = self._calculateNumberOfSequences()
if normalizationFile is not None:
self._setNormalization(normalizationFile)
self._setInputAndOutputDimensions(num_outputs)
def _initHdfFileHandlers(self, hdfFile):
"""Initialize HDF file handlers
:type hdfFile: str
:param hdfFile: path to an HDF file with sequences or to a bundle file
which should contain one path to an HDF file per line
:see: BundleFile.BundleFile
"""
self._filePaths = []
self._fileHandlers = []
if hdfFile.endswith('.bundle'):
# a bundle file containing a list of hdf files is given
bundle = BundleFile(hdfFile)
for hdfFilePath in bundle.datasetFilePaths:
self._filePaths.append(hdfFilePath)
self._fileHandlers.append(h5py.File(hdfFilePath, 'r'))
else:
# only a single hdf file is given
self._filePaths.append(hdfFile)
self._fileHandlers.append(h5py.File(hdfFile, 'r'))
def _calculateNumberOfSequences(self):
"""Calculate and return the number of sequences in the dataset.
This method also initializes a sequences map which maps sequence
indices into HDF file handlers.
:rtype: int
:return: the number of sequences in the dataset
"""
# initialize a sequence map to map the sequence index
# from an hdf file into the corresponding
# hdfFile and hdf-dataset name,
# but it could e.g. be used for shuffling sequences as well
self._seqMap = {}
seqCounter = 0
for fhIdx, fh in enumerate(self._fileHandlers):
for k in fh['inputs'].keys():
self._seqMap[seqCounter] = (fhIdx, k)
seqCounter += 1
return seqCounter
def _setNormalization(self, normalizationFile):
"""Set optional normalization (mean and variance).
Mean and variance are set only if they are provided.
:type normalizationFile: string
:param normalizationFile: path to an HDF normalization file which contains
optional datasets "mean" and "variance".
:see: NormalizationData.NormalizationData
"""
if not os.path.isfile(normalizationFile):
raise IOError(normalizationFile + ' does not exist')
self._normData = NormalizationData(normalizationFile)
def _setInputAndOutputDimensions(self, num_outputs):
"""Set properties which correspond to input and output dimensions.
:type num_outputs: int
:param num_outputs: dimensionality of output features. used only if
the dataset does not have output features.
"""
someSequence = self._collect_single_seq(0)
self.num_inputs = someSequence.get_data('data').shape[1]
if 'outputs' in self._fileHandlers[0]:
self.num_outputs = {
'classes': (someSequence.get_data('classes').shape[1], 2)
}
else:
# in this case no output data is in the hdf file and
# therfore the output dimension needs to be given
# as an argument through the config file
if num_outputs is None:
raise ValueError(
'if no output data is contained in StereoDataset'
' the output dimension has to be specified by num_outputs'
)
self.num_outputs = {'classes': (num_outputs, 2)}
def get_data_dim(self, key):
"""This is copied from CachedDataset2 but the assertion is
removed (see CachedDataset2.py)
:type key: str
:rtype: int
:return: number of classes, no matter if sparse or not
"""
if key == 'data':
return self.num_inputs
if key in self.num_outputs:
d = self.num_outputs[key][0]
return d
self._load_something()
if len(self.added_data[0].get_data(key).shape) == 1:
return super(CachedDataset2, self).get_data_dim(key) # unknown
assert len(self.added_data[0].get_data(key).shape) == 2
return self.added_data[0].get_data(key).shape[1]
def __del__(self):
"""Closes HDF file handlers.
"""
for fh in self._fileHandlers:
try:
fh.close()
except Exception:
pass
@property
def num_seqs(self):
"""Returns the number of sequences of the dataset
:rtype: int
:return: the number of sequences of the dataset.
"""
# has been set during initialization of dataset ...
if self._num_seqs is not None:
return self._num_seqs
# ... but for some reason _num_seqs is not set at specific points in the
# execution of rnn.py therefore the following is a saveguard to fall back on
self._num_seqs = self._calculateNumberOfSequences()
return self._num_seqs
def _collect_single_seq(self, seq_idx):
"""Returns the sequence specified by the index seq_idx.
Normalization is applied to the input features if mean and variance
have been specified during dataset creating (see the constructor).
:type seq_idx: int
:rtype: DatasetSeq | None
:returns: None if seq_idx >= num_seqs or the corresponding sequence.
"""
if seq_idx >= self.num_seqs:
return None
# map the seq_idx to the shuffled sequence indices
if self._seq_index_list is None:
self.init_seq_order()
shuf_seq_idx = self._seq_index_list[seq_idx]
seqMapping = self._seqMap[shuf_seq_idx]
fileIdx = seqMapping[0]
datasetName = seqMapping[1]
fileHandler = self._fileHandlers[fileIdx]
inputFeatures = fileHandler['inputs'][datasetName][...]
targets = None
if 'outputs' in fileHandler:
targets = fileHandler['outputs'][datasetName][...]
# optional normalization
if self._normData is not None:
assert isinstance(self._normData, NormalizationData)
# inputs
if self._flag_normalizeInputs:
inputFeatures = StereoHdfDataset._normalizeVector(inputFeatures, self._normData.inputMean, self._normData.inputVariance)
# outputs
if self._flag_normalizeTargets:
targets = StereoHdfDataset._normalizeVector(targets, self._normData.outputMean, self._normData.outputVariance)
# enforce float32 to enable Theano optimizations
inputFeatures = inputFeatures.astype(np.float32)
if targets is not None:
targets = targets.astype(np.float32)
return DatasetSeq(seq_idx, inputFeatures, targets)
@staticmethod
def _normalizeVector(v, mean, variance):
"""Helper method.
Applies optional normalization to the given vector.
:type v: numpy.ndarray | None
:param v: vector if available or None otherwise
:type mean: numpy.ndarray | None
:param mean: mean
:type variance: numpy.ndarray | None
:param variance: variance
:rtype: numpy.ndarray | None
:return: normalized vector or None if it was None
"""
if v is None:
return v
if mean is not None:
v -= mean
if variance is not None:
v /= np.sqrt(variance)
return v
class DatasetWithTimeContext(StereoHdfDataset):
"""This dataset composes a context feature by stacking together time frames.
"""
def __init__(self, hdfFile, tau=1, **kwargs):
"""Constructor
:type hdfFile: string
:param hdfFile: see the StereoHdfDataset
:type tau: int
:param tau: how many time frames should be on the left and on the right.
E.g. if tau = 2 then the context feature will be created
by stacking two neighboring time frames from left and
two neighboring time frames from right:
newInputFeature = [ x_{t-2}, x_{t-1}, x_t, x_{t+1}, x_{t+2} ].
In general new feature will have shape
(2 * tau + 1) * originalFeatureDimensionality
Output features are not changed.
:type kwargs: dictionary
:param kwargs: the rest of the arguments passed to the StereoHdfDataset
"""
if tau <= 0:
raise ValueError('context parameter tau should be greater than zero')
self._tau = tau
super(DatasetWithTimeContext, self).__init__(hdfFile, **kwargs)
def _collect_single_seq(self, seq_idx):
"""this method implements stacking the features
:type seq_idx: int
:param seq_idx: index of a sequence
:rtype: DatasetSeq
:return: DatasetSeq
"""
if seq_idx >= self.num_seqs:
return None
originalSeq = super(DatasetWithTimeContext, self)._collect_single_seq(
seq_idx
)
inputFeatures = originalSeq.get_data('data')
frames, bins = inputFeatures.shape
leftContext = deque()
rightContext = deque()
inFeatWithContext = []
for i in range(self._tau):
leftContext.append(np.zeros(bins))
if i + 1 < frames:
rightContext.append(inputFeatures[i + 1, ...])
else:
rightContext.append(np.zeros(bins))
for t in range(frames):
f = inputFeatures[t, ...]
newFeature = np.concatenate([np.concatenate(leftContext, axis=0), f, np.concatenate(rightContext, axis=0)],axis=0)
inFeatWithContext.append(newFeature)
leftContext.popleft()
leftContext.append(f)
rightContext.popleft()
if t + 1 + self._tau < frames:
rightContext.append(inputFeatures[t + 1 + self._tau, ...])
else:
rightContext.append(np.zeros(bins))
inputFeatures = np.array(inFeatWithContext)
targets = None
if 'classes' in originalSeq.get_data_keys():
targets = originalSeq.get_data('classes')
return DatasetSeq(seq_idx, inputFeatures, targets)