[b48499]: / test / test_augmenters.py

Download this file

349 lines (290 with data), 11.7 kB

  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
"""
"""
import re
import numpy as np
import pytest
import torch
from torch_ecg.augmenters import (
Augmenter,
AugmenterManager,
BaselineWanderAugmenter,
CutMix,
LabelSmooth,
Mixup,
RandomFlip,
RandomMasking,
RandomRenormalize,
StretchCompress,
StretchCompressOffline,
)
from torch_ecg.augmenters.baseline_wander import _gen_baseline_wander
from torch_ecg.cfg import CFG
SIG_LEN = 2000
BATCH_SIZE = 2
N_LEADS = 12
def test_base_augmenter():
with pytest.raises(
TypeError,
match=f"Can't instantiate abstract class {Augmenter.__name__}",
):
aug = Augmenter()
def test_augmenter_manager():
# all use default config
config = CFG(
random=False,
fs=500,
baseline_wander={},
label_smooth={},
mixup={},
random_flip={},
random_masking={},
random_renormalize={},
stretch_compress={},
)
am = AugmenterManager.from_config(config)
sig = torch.randn(BATCH_SIZE, N_LEADS, SIG_LEN)
label = torch.randint(0, 2, (BATCH_SIZE, 26), dtype=torch.float32)
mask1 = torch.randint(0, 2, (BATCH_SIZE, SIG_LEN, 3), dtype=torch.float32)
mask2 = torch.randint(0, 3, (BATCH_SIZE, SIG_LEN), dtype=torch.long)
sig, label, mask1, mask2 = am(sig, label, mask1, mask2)
am.rearrange(
new_ordering=[
"stretch_compress",
"random_masking",
"baseline_wander",
"random_renormalize",
"random_flip",
"label_smooth",
"mixup",
]
)
am.random = True
sig, label, mask1, mask2 = am(sig, label, mask1, mask2)
with pytest.warns(RuntimeWarning, match="The augmenters are applied in random order"):
am.random = True
am.rearrange(
new_ordering=[
"mixup",
"random_masking",
"random_flip",
"baseline_wander",
"random_renormalize",
"label_smooth",
"stretch_compress",
]
)
am.random = False
with pytest.raises(AssertionError, match="Duplicate augmenter names"):
am.rearrange(
new_ordering=[
"stretch_compress",
"random_masking",
"baseline_wander",
"random_renormalize",
"random_flip",
"label_smooth",
"mixup",
"random_masking",
]
)
with pytest.raises(AssertionError, match="Number of augmenters mismatch"):
am.rearrange(
new_ordering=[
"stretch_compress",
"random_masking",
"baseline_wander",
"random_renormalize",
"random_flip",
"label_smooth",
]
)
with pytest.raises(AssertionError, match="Unknown augmenter name: `.+`"):
am.rearrange(
new_ordering=[
"stretch_compress",
"random_masking",
"baseline_wander",
"random_normalize", # typo
"random_flip",
"label_smooth",
"mixup",
]
)
assert re.search("augmenters = \\[", repr(am))
def test_baseline_wander_augmenter():
blw = BaselineWanderAugmenter(300, prob=0.7, inplace=False)
sig = torch.randn(BATCH_SIZE, N_LEADS, SIG_LEN)
label = torch.randint(0, 2, (BATCH_SIZE, 26), dtype=torch.float32)
sig, _ = blw(sig, label)
assert str(blw) == repr(blw)
noise = _gen_baseline_wander(
siglen=sig.shape[-1],
fs=blw.fs,
bw_fs=blw.bw_fs,
amplitude=blw.ampl_ratio[1],
amplitude_gaussian=blw.gaussian[1],
)
noise = _gen_baseline_wander(
siglen=sig.shape[-1],
fs=blw.fs,
bw_fs=1.5,
amplitude=0.05,
amplitude_gaussian=blw.gaussian[1],
)
def test_cutmix_augmenter():
sig = torch.randn(BATCH_SIZE, N_LEADS, SIG_LEN)
label = torch.randint(0, 2, (BATCH_SIZE, 26), dtype=torch.float32)
mask = torch.randint(0, 2, (BATCH_SIZE, SIG_LEN, 3), dtype=torch.float32)
label = torch.randint(0, 2, (BATCH_SIZE, 26), dtype=torch.float32)
cm = CutMix(fs=500, prob=0.7, beta=0.6)
sig, label, mask = cm(sig, label, mask)
assert sig.shape == (BATCH_SIZE, N_LEADS, SIG_LEN)
assert label.shape == (BATCH_SIZE, 26)
assert mask.shape == (BATCH_SIZE, SIG_LEN, 3)
sig = torch.randn(BATCH_SIZE, N_LEADS, SIG_LEN)
label = torch.randint(0, 2, (BATCH_SIZE, 26), dtype=torch.float32)
mask = torch.randint(0, 2, (BATCH_SIZE, SIG_LEN, 3), dtype=torch.float32)
label = torch.randint(0, 2, (BATCH_SIZE, 26), dtype=torch.float32)
cm = CutMix(fs=500, prob=0.4, inplace=False, num_mix=2)
new_sig, new_label, new_mask = cm(sig, label, mask)
assert new_sig.shape == (BATCH_SIZE, N_LEADS, SIG_LEN)
assert new_label.shape == (BATCH_SIZE, 26)
assert new_mask.shape == (BATCH_SIZE, SIG_LEN, 3)
new_sig, new_mask = cm(sig, mask)
assert new_sig.shape == (BATCH_SIZE, N_LEADS, SIG_LEN)
assert new_mask.shape == (BATCH_SIZE, SIG_LEN, 3)
assert str(cm) == repr(cm)
with pytest.raises(AssertionError, match="`label` should NOT be categorical labels"):
label = torch.randint(0, 26, (BATCH_SIZE,), dtype=torch.long)
cm(sig, label)
with pytest.raises(AssertionError, match="`num_mix` must be a positive integer, but got `.+`"):
cm = CutMix(fs=500, num_mix=0)
with pytest.raises(AssertionError, match="Probability must be between 0 and 1"):
cm = CutMix(fs=500, prob=1.1)
with pytest.raises(
AssertionError,
match="`alpha` and `beta` must be positive, but got `.+` and `.+`",
):
cm = CutMix(fs=500, alpha=0, beta=0)
def test_label_smooth():
ls = LabelSmooth(inplace=False)
label = torch.randint(0, 2, (BATCH_SIZE, 26), dtype=torch.float32)
_, label = ls(None, label)
ls = LabelSmooth(smoothing=0.0)
label = torch.randint(0, 2, (BATCH_SIZE, 26), dtype=torch.float32)
_, label = ls(None, label)
assert str(ls) == repr(ls)
def test_mixup():
mixup = Mixup()
sig = torch.randn(BATCH_SIZE, N_LEADS, SIG_LEN)
label = torch.randint(0, 2, (BATCH_SIZE, 26), dtype=torch.float32)
sig, label = mixup(sig, label)
mixup = Mixup(inplace=False)
sig = torch.randn(BATCH_SIZE, N_LEADS, SIG_LEN)
label = torch.randint(0, 2, (BATCH_SIZE, 26), dtype=torch.float32)
sig, label = mixup(sig, label)
assert str(mixup) == repr(mixup)
def test_random_flip():
rf = RandomFlip()
sig = torch.randn(BATCH_SIZE, N_LEADS, SIG_LEN)
sig, _ = rf(sig, None)
rf = RandomFlip(inplace=False, per_channel=False)
sig = torch.randn(BATCH_SIZE, N_LEADS, SIG_LEN)
sig, _ = rf(sig, None)
rf = RandomFlip(prob=0.0, per_channel=False)
sig = torch.randn(BATCH_SIZE, N_LEADS, SIG_LEN)
sig, _ = rf(sig, None)
assert str(rf) == repr(rf)
def test_random_masking():
rm = RandomMasking(fs=500, prob=0.7)
sig = torch.randn(BATCH_SIZE, N_LEADS, SIG_LEN)
critical_points = [np.arange(250, SIG_LEN - 250, step=400) for _ in range(BATCH_SIZE)]
sig, _ = rm(sig, None, critical_points=critical_points)
rm = RandomMasking(fs=500, prob=0.3, inplace=False)
sig = torch.randn(BATCH_SIZE, N_LEADS, SIG_LEN)
sig, _ = rm(sig, None, critical_points=critical_points)
rm = RandomMasking(fs=500, prob=0.0)
sig = torch.randn(BATCH_SIZE, N_LEADS, SIG_LEN)
sig, _ = rm(sig, None, critical_points=critical_points)
assert str(rm) == repr(rm)
def test_random_renormalize():
rrn = RandomRenormalize(per_channel=True, prob=0.7)
sig = torch.randn(BATCH_SIZE, N_LEADS, SIG_LEN)
sig, _ = rrn(sig, None)
# TODO: fix errors in the following tests
# rrn = RandomRenormalize(mean=np.zeros((N_LEADS, 1)), std=np.ones((N_LEADS, 1)), per_channel=True)
# sig = torch.randn(BATCH_SIZE, N_LEADS, SIG_LEN)
# sig, _ = rrn(sig, None)
rrn = RandomRenormalize(mean=np.zeros((N_LEADS,)), std=np.ones((N_LEADS,)), inplace=False)
sig = torch.randn(BATCH_SIZE, N_LEADS, SIG_LEN)
sig, _ = rrn(sig, None)
rrn = RandomRenormalize(prob=0.0)
sig = torch.randn(BATCH_SIZE, N_LEADS, SIG_LEN)
sig, _ = rrn(sig, None)
assert str(rrn) == repr(rrn)
def test_stretch_compress():
sc = StretchCompress(inplace=False)
sig = torch.randn((BATCH_SIZE, N_LEADS, SIG_LEN))
# labels = torch.randint(0, 2, (BATCH_SIZE, SIG_LEN, 26))
label = torch.randint(0, 2, (BATCH_SIZE, 26), dtype=torch.float32)
mask = torch.randint(0, 2, (BATCH_SIZE, SIG_LEN, 3), dtype=torch.float32)
sig, label, mask = sc(sig, label, mask)
assert sig.shape == (BATCH_SIZE, N_LEADS, SIG_LEN)
assert label.shape == (BATCH_SIZE, 26)
assert mask.shape == (BATCH_SIZE, SIG_LEN, 3)
label = torch.randint(0, 2, (BATCH_SIZE, SIG_LEN // 2, 26), dtype=torch.float32)
assert label.shape == (BATCH_SIZE, SIG_LEN // 2, 26)
sig = torch.randn((BATCH_SIZE, N_LEADS, SIG_LEN))
# labels = torch.randint(0, 2, (BATCH_SIZE, SIG_LEN, 26))
label = torch.randint(0, 2, (BATCH_SIZE, 26), dtype=torch.float32)
mask = torch.randint(0, 2, (BATCH_SIZE, SIG_LEN // 8, 3), dtype=torch.float32)
for _ in range(5):
# generate 5 times
sig, label, mask = sc._generate(sig, label, mask)
# generate with only sig
sig = sc._generate(sig)
sc = StretchCompress(prob=0.0)
sig = torch.randn((BATCH_SIZE, N_LEADS, SIG_LEN))
# labels = torch.randint(0, 2, (BATCH_SIZE, SIG_LEN, 26))
label = torch.randint(0, 2, (BATCH_SIZE, 26), dtype=torch.float32)
mask = torch.randint(0, 2, (BATCH_SIZE, SIG_LEN // 8, 3), dtype=torch.float32)
sig, label, mask = sc(sig, label, mask)
assert sig.shape == (BATCH_SIZE, N_LEADS, SIG_LEN)
assert label.shape == (BATCH_SIZE, 26)
assert mask.shape == (BATCH_SIZE, SIG_LEN // 8, 3)
sig = torch.randn((BATCH_SIZE, N_LEADS, SIG_LEN))
# labels = torch.randint(0, 2, (BATCH_SIZE, SIG_LEN, 26))
label = torch.randint(0, 2, (BATCH_SIZE, 26), dtype=torch.float32)
mask = torch.randint(0, 2, (BATCH_SIZE, SIG_LEN // 8, 3), dtype=torch.float32)
for _ in range(5):
# generate 5 times
sig, label, mask = sc._generate(sig, label, mask)
# generate with only sig
sig = sc._generate(sig)
assert str(sc) == repr(sc)
def test_stretch_compress_offline():
sco = StretchCompressOffline()
seglen = 600
sig = torch.randn((N_LEADS, 60000)).numpy()
labels = torch.ones((60000, 3)).numpy().astype(int)
masks = torch.ones((60000, 1)).numpy().astype(int)
segments = sco(seglen, sig, labels, masks, critical_points=[10000, 30000])
sig = torch.randn((N_LEADS, 60)).numpy()
labels = torch.ones((60, 3)).numpy().astype(int)
masks = torch.ones((60, 1)).numpy().astype(int)
segments = sco(seglen, sig, labels, masks)
sig = torch.randn((N_LEADS, 800)).numpy()
labels = torch.ones((800, 3)).numpy().astype(int)
masks = torch.ones((800, 1)).numpy().astype(int)
segments = sco(seglen, sig, labels, masks)
assert str(sco) == repr(sco)
for _ in range(5):
# generate 5 times
aug_seg, aug_labels, aug_masks, start_idx, end_idx = sco._StretchCompressOffline__generate_segment(
seglen, sig, labels, masks, end_idx=sig.shape[-1] + 200
)
assert end_idx == sig.shape[-1]
aug_seg, aug_labels, aug_masks, start_idx, end_idx = sco._StretchCompressOffline__generate_segment(
seglen, sig, labels, masks, end_idx=seglen - 200
)
assert start_idx == 0