-
Notifications
You must be signed in to change notification settings - Fork 7
/
loss_metrics.py
645 lines (522 loc) · 20.5 KB
/
loss_metrics.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
"""Content loss metrics for Sup3r"""
import numpy as np
import tensorflow as tf
from tensorflow.keras.losses import MeanAbsoluteError, MeanSquaredError
def gaussian_kernel(x1, x2, sigma=1.0):
"""Gaussian kernel for mmd content loss
Parameters
----------
x1 : tf.tensor
synthetic generator output
(n_obs, spatial_1, spatial_2, temporal, features)
x2 : tf.tensor
high resolution data
(n_obs, spatial_1, spatial_2, temporal, features)
sigma : float
Standard deviation for gaussian kernel
Returns
-------
tf.tensor
kernel output tensor
References
----------
Following MMD implementation in https://github.com/lmjohns3/theanets
"""
# The expand dims + subtraction compares every entry for the dimension
# prior to the expanded dimension to every other entry. So expand_dims with
# axis=1 will compare every observation along axis=0 to every other
# observation along axis=0.
result = tf.exp(-0.5 * tf.reduce_sum(
(tf.expand_dims(x1, axis=1) - x2)**2, axis=-1) / sigma**2)
return result
class ExpLoss(tf.keras.losses.Loss):
"""Loss class for squared exponential difference"""
def __call__(self, x1, x2):
"""Exponential difference loss function
Parameters
----------
x1 : tf.tensor
synthetic generator output
(n_observations, spatial_1, spatial_2, temporal, features)
x2 : tf.tensor
high resolution data
(n_observations, spatial_1, spatial_2, temporal, features)
Returns
-------
tf.tensor
0D tensor with loss value
"""
return tf.reduce_mean(1 - tf.exp(-(x1 - x2)**2))
class MseExpLoss(tf.keras.losses.Loss):
"""Loss class for mse + squared exponential difference"""
MSE_LOSS = MeanSquaredError()
def __call__(self, x1, x2):
"""Mse + Exponential difference loss function
Parameters
----------
x1 : tf.tensor
synthetic generator output
(n_observations, spatial_1, spatial_2, temporal, features)
x2 : tf.tensor
high resolution data
(n_observations, spatial_1, spatial_2, temporal, features)
Returns
-------
tf.tensor
0D tensor with loss value
"""
mse = self.MSE_LOSS(x1, x2)
exp = tf.reduce_mean(1 - tf.exp(-(x1 - x2)**2))
return mse + exp
class MmdLoss(tf.keras.losses.Loss):
"""Loss class for max mean discrepancy loss"""
def __call__(self, x1, x2, sigma=1.0):
"""Maximum mean discrepancy (MMD) based on Gaussian kernel function
for keras models
Parameters
----------
x1 : tf.tensor
synthetic generator output
(n_observations, spatial_1, spatial_2, temporal, features)
x2 : tf.tensor
high resolution data
(n_observations, spatial_1, spatial_2, temporal, features)
sigma : float
standard deviation for gaussian kernel
Returns
-------
tf.tensor
0D tensor with loss value
"""
mmd = tf.reduce_mean(gaussian_kernel(x1, x1, sigma))
mmd += tf.reduce_mean(gaussian_kernel(x2, x2, sigma))
mmd -= tf.reduce_mean(2 * gaussian_kernel(x1, x2, sigma))
return mmd
class MmdMseLoss(tf.keras.losses.Loss):
"""Loss class for MMD + MSE"""
MMD_LOSS = MmdLoss()
MSE_LOSS = MeanSquaredError()
def __call__(self, x1, x2, sigma=1.0):
"""Maximum mean discrepancy (MMD) based on Gaussian kernel function
for keras models plus the typical MSE loss.
Parameters
----------
x1 : tf.tensor
synthetic generator output
(n_observations, spatial_1, spatial_2, temporal, features)
x2 : tf.tensor
high resolution data
(n_observations, spatial_1, spatial_2, temporal, features)
sigma : float
standard deviation for gaussian kernel
Returns
-------
tf.tensor
0D tensor with loss value
"""
mmd = self.MMD_LOSS(x1, x2, sigma=sigma)
mse = self.MSE_LOSS(x1, x2)
return (mmd + mse) / 2
class CoarseMseLoss(tf.keras.losses.Loss):
"""Loss class for coarse mse on spatial average of 5D tensor"""
MSE_LOSS = MeanSquaredError()
def __call__(self, x1, x2):
"""Exponential difference loss function
Parameters
----------
x1 : tf.tensor
synthetic generator output
(n_observations, spatial_1, spatial_2, temporal, features)
x2 : tf.tensor
high resolution data
(n_observations, spatial_1, spatial_2, temporal, features)
Returns
-------
tf.tensor
0D tensor with loss value
"""
x1_coarse = tf.reduce_mean(x1, axis=(1, 2))
x2_coarse = tf.reduce_mean(x2, axis=(1, 2))
return self.MSE_LOSS(x1_coarse, x2_coarse)
class SpatialExtremesOnlyLoss(tf.keras.losses.Loss):
"""Loss class that encourages accuracy of the min/max values in the
spatial domain. This does not include an additional MAE term"""
MAE_LOSS = MeanAbsoluteError()
def __call__(self, x1, x2):
"""Custom content loss that encourages temporal min/max accuracy
Parameters
----------
x1 : tf.tensor
synthetic generator output
(n_observations, spatial_1, spatial_2, features)
x2 : tf.tensor
high resolution data
(n_observations, spatial_1, spatial_2, features)
Returns
-------
tf.tensor
0D tensor with loss value
"""
x1_min = tf.reduce_min(x1, axis=(1, 2))
x2_min = tf.reduce_min(x2, axis=(1, 2))
x1_max = tf.reduce_max(x1, axis=(1, 2))
x2_max = tf.reduce_max(x2, axis=(1, 2))
mae_min = self.MAE_LOSS(x1_min, x2_min)
mae_max = self.MAE_LOSS(x1_max, x2_max)
return (mae_min + mae_max) / 2
class SpatialExtremesLoss(tf.keras.losses.Loss):
"""Loss class that encourages accuracy of the min/max values in the
spatial domain"""
MAE_LOSS = MeanAbsoluteError()
EX_LOSS = SpatialExtremesOnlyLoss()
def __init__(self, weight=1.0):
"""Initialize the loss with given weight
Parameters
----------
weight : float
Weight for min/max loss terms. Setting this to zero turns
loss into MAE.
"""
super().__init__()
self._weight = weight
def __call__(self, x1, x2):
"""Custom content loss that encourages temporal min/max accuracy
Parameters
----------
x1 : tf.tensor
synthetic generator output
(n_observations, spatial_1, spatial_2, features)
x2 : tf.tensor
high resolution data
(n_observations, spatial_1, spatial_2, features)
Returns
-------
tf.tensor
0D tensor with loss value
"""
mae = self.MAE_LOSS(x1, x2)
ex_mae = self.EX_LOSS(x1, x2)
return (mae + 2 * self._weight * ex_mae) / 3
class TemporalExtremesOnlyLoss(tf.keras.losses.Loss):
"""Loss class that encourages accuracy of the min/max values in the
timeseries. This does not include an additional mae term"""
MAE_LOSS = MeanAbsoluteError()
def __call__(self, x1, x2):
"""Custom content loss that encourages temporal min/max accuracy
Parameters
----------
x1 : tf.tensor
synthetic generator output
(n_observations, spatial_1, spatial_2, temporal, features)
x2 : tf.tensor
high resolution data
(n_observations, spatial_1, spatial_2, temporal, features)
Returns
-------
tf.tensor
0D tensor with loss value
"""
x1_min = tf.reduce_min(x1, axis=3)
x2_min = tf.reduce_min(x2, axis=3)
x1_max = tf.reduce_max(x1, axis=3)
x2_max = tf.reduce_max(x2, axis=3)
mae_min = self.MAE_LOSS(x1_min, x2_min)
mae_max = self.MAE_LOSS(x1_max, x2_max)
return (mae_min + mae_max) / 2
class TemporalExtremesLoss(tf.keras.losses.Loss):
"""Loss class that encourages accuracy of the min/max values in the
timeseries"""
MAE_LOSS = MeanAbsoluteError()
EX_LOSS = TemporalExtremesOnlyLoss()
def __init__(self, weight=1.0):
"""Initialize the loss with given weight
Parameters
----------
weight : float
Weight for min/max loss terms. Setting this to zero turns
loss into MAE.
"""
super().__init__()
self._weight = weight
def __call__(self, x1, x2):
"""Custom content loss that encourages temporal min/max accuracy
Parameters
----------
x1 : tf.tensor
synthetic generator output
(n_observations, spatial_1, spatial_2, temporal, features)
x2 : tf.tensor
high resolution data
(n_observations, spatial_1, spatial_2, temporal, features)
Returns
-------
tf.tensor
0D tensor with loss value
"""
mae = self.MAE_LOSS(x1, x2)
ex_mae = self.EX_LOSS(x1, x2)
return (mae + 2 * self._weight * ex_mae) / 3
class SpatiotemporalExtremesLoss(tf.keras.losses.Loss):
"""Loss class that encourages accuracy of the min/max values across both
space and time"""
MAE_LOSS = MeanAbsoluteError()
S_EX_LOSS = SpatialExtremesOnlyLoss()
T_EX_LOSS = TemporalExtremesOnlyLoss()
def __init__(self, spatial_weight=1.0, temporal_weight=1.0):
"""Initialize the loss with given weight
Parameters
----------
spatial_weight : float
Weight for spatial min/max loss terms.
temporal_weight : float
Weight for temporal min/max loss terms.
"""
super().__init__()
self.s_weight = spatial_weight
self.t_weight = temporal_weight
def __call__(self, x1, x2):
"""Custom content loss that encourages spatiotemporal min/max accuracy.
Parameters
----------
x1 : tf.tensor
synthetic generator output
(n_observations, spatial_1, spatial_2, temporal, features)
x2 : tf.tensor
high resolution data
(n_observations, spatial_1, spatial_2, temporal, features)
Returns
-------
tf.tensor
0D tensor with loss value
"""
mae = self.MAE_LOSS(x1, x2)
s_ex_mae = self.S_EX_LOSS(x1, x2)
t_ex_mae = self.T_EX_LOSS(x1, x2)
return (mae + 2 * self.s_weight * s_ex_mae
+ 2 * self.t_weight * t_ex_mae) / 5
class SpatialFftOnlyLoss(tf.keras.losses.Loss):
"""Loss class that encourages accuracy of the spatial frequency spectrum"""
MAE_LOSS = MeanAbsoluteError()
@staticmethod
def _freq_weights(x):
"""Get product of squared frequencies to weight frequency amplitudes"""
k0 = np.array([k**2 for k in range(x.shape[1])])
k1 = np.array([k**2 for k in range(x.shape[2])])
freqs = np.multiply.outer(k0, k1)
freqs = tf.convert_to_tensor(freqs[np.newaxis, ..., np.newaxis])
return tf.cast(freqs, x.dtype)
def _fft(self, x):
"""Apply needed transpositions and fft operation."""
x_hat = tf.transpose(x, perm=[3, 0, 1, 2])
x_hat = tf.signal.fft2d(tf.cast(x_hat, tf.complex64))
x_hat = tf.transpose(x_hat, perm=[1, 2, 3, 0])
x_hat = tf.cast(tf.abs(x_hat), x.dtype)
x_hat = tf.math.multiply(self._freq_weights(x), x_hat)
return tf.math.log(1 + x_hat)
def __call__(self, x1, x2):
"""Custom content loss that encourages frequency domain accuracy
Parameters
----------
x1 : tf.tensor
synthetic generator output
(n_observations, spatial_1, spatial_2, features)
x2 : tf.tensor
high resolution data
(n_observations, spatial_1, spatial_2, features)
Returns
-------
tf.tensor
0D tensor with loss value
"""
x1_hat = self._fft(x1)
x2_hat = self._fft(x2)
return self.MAE_LOSS(x1_hat, x2_hat)
class SpatiotemporalFftOnlyLoss(tf.keras.losses.Loss):
"""Loss class that encourages accuracy of the spatiotemporal frequency
spectrum"""
MAE_LOSS = MeanAbsoluteError()
@staticmethod
def _freq_weights(x):
"""Get product of squared frequencies to weight frequency amplitudes"""
k0 = np.array([k**2 for k in range(x.shape[1])])
k1 = np.array([k**2 for k in range(x.shape[2])])
f = np.array([f**2 for f in range(x.shape[3])])
freqs = np.multiply.outer(k0, k1)
freqs = np.multiply.outer(freqs, f)
freqs = tf.convert_to_tensor(freqs[np.newaxis, ..., np.newaxis])
return tf.cast(freqs, x.dtype)
def _fft(self, x):
"""Apply needed transpositions and fft operation."""
x_hat = tf.transpose(x, perm=[4, 0, 1, 2, 3])
x_hat = tf.signal.fft3d(tf.cast(x_hat, tf.complex64))
x_hat = tf.transpose(x_hat, perm=[1, 2, 3, 4, 0])
x_hat = tf.cast(tf.abs(x_hat), x.dtype)
x_hat = tf.math.multiply(self._freq_weights(x), x_hat)
return tf.math.log(1 + x_hat)
def __call__(self, x1, x2):
"""Custom content loss that encourages frequency domain accuracy
Parameters
----------
x1 : tf.tensor
synthetic generator output
(n_observations, spatial_1, spatial_2, temporal, features)
x2 : tf.tensor
high resolution data
(n_observations, spatial_1, spatial_2, temporal, features)
Returns
-------
tf.tensor
0D tensor with loss value
"""
x1_hat = self._fft(x1)
x2_hat = self._fft(x2)
return self.MAE_LOSS(x1_hat, x2_hat)
class StExtremesFftLoss(tf.keras.losses.Loss):
"""Loss class that encourages accuracy of the min/max values across both
space and time as well as frequency domain accuracy."""
def __init__(self, spatial_weight=1.0, temporal_weight=1.0,
fft_weight=1.0):
"""Initialize the loss with given weight
Parameters
----------
spatial_weight : float
Weight for spatial min/max loss terms.
temporal_weight : float
Weight for temporal min/max loss terms.
fft_weight : float
Weight for the fft loss term.
"""
super().__init__()
self.st_ex_loss = SpatiotemporalExtremesLoss(spatial_weight,
temporal_weight)
self.fft_loss = SpatiotemporalFftOnlyLoss()
self.fft_weight = fft_weight
def __call__(self, x1, x2):
"""Custom content loss that encourages spatiotemporal min/max accuracy
and fft accuracy.
Parameters
----------
x1 : tf.tensor
synthetic generator output
(n_observations, spatial_1, spatial_2, temporal, features)
x2 : tf.tensor
high resolution data
(n_observations, spatial_1, spatial_2, temporal, features)
Returns
-------
tf.tensor
0D tensor with loss value
"""
return (5 * self.st_ex_loss(x1, x2)
+ self.fft_weight * self.fft_loss(x1, x2)) / 6
class LowResLoss(tf.keras.losses.Loss):
"""Content loss that is calculated by coarsening the synthetic and true
high-resolution data pairs and then performing the pointwise content loss
on the low-resolution fields"""
EX_LOSS_METRICS = {'SpatialExtremesOnlyLoss': SpatialExtremesOnlyLoss,
'TemporalExtremesOnlyLoss': TemporalExtremesOnlyLoss,
}
def __init__(self, s_enhance=1, t_enhance=1, t_method='average',
tf_loss='MeanSquaredError', ex_loss=None):
"""Initialize the loss with given weight
Parameters
----------
s_enhance : int
factor by which to coarsen spatial dimensions. 1 will keep the
spatial axes as high-res
t_enhance : int
factor by which to coarsen temporal dimension. 1 will keep the
temporal axes as high-res
t_method : str
Accepted options: [subsample, average]
Subsample will take every t_enhance-th time step, average will
average over t_enhance time steps
tf_loss : str
The tensorflow loss function to operate on the low-res fields. Must
be the name of a loss class that can be retrieved from
``tf.keras.losses`` e.g., "MeanSquaredError" or "MeanAbsoluteError"
ex_loss : None | str
Optional additional loss metric evaluating the spatial or temporal
extremes of the high-res data. Can be "SpatialExtremesOnlyLoss" or
"TemporalExtremesOnlyLoss" (keys in ``EX_LOSS_METRICS``).
"""
super().__init__()
self._s_enhance = s_enhance
self._t_enhance = t_enhance
self._t_method = str(t_method).casefold()
self._tf_loss = getattr(tf.keras.losses, tf_loss)()
self._ex_loss = ex_loss
if self._ex_loss is not None:
self._ex_loss = self.EX_LOSS_METRICS[self._ex_loss]()
def _s_coarsen_4d_tensor(self, tensor):
"""Perform spatial coarsening on a 4D tensor of shape
(n_obs, spatial_1, spatial_2, features)"""
shape = tensor.shape
tensor = tf.reshape(tensor,
(shape[0],
shape[1] // self._s_enhance, self._s_enhance,
shape[2] // self._s_enhance, self._s_enhance,
shape[3]))
tensor = tf.math.reduce_sum(tensor, axis=(2, 4)) / self._s_enhance**2
return tensor
def _s_coarsen_5d_tensor(self, tensor):
"""Perform spatial coarsening on a 5D tensor of shape
(n_obs, spatial_1, spatial_2, time, features)"""
shape = tensor.shape
tensor = tf.reshape(tensor,
(shape[0],
shape[1] // self._s_enhance, self._s_enhance,
shape[2] // self._s_enhance, self._s_enhance,
shape[3], shape[4]))
tensor = tf.math.reduce_sum(tensor, axis=(2, 4)) / self._s_enhance**2
return tensor
def _t_coarsen_sample(self, tensor):
"""Perform temporal subsampling on a 5D tensor of shape
(n_obs, spatial_1, spatial_2, time, features)"""
assert len(tensor.shape) == 5
tensor = tensor[:, :, :, ::self._t_enhance, :]
return tensor
def _t_coarsen_avg(self, tensor):
"""Perform temporal coarsening on a 5D tensor of shape
(n_obs, spatial_1, spatial_2, time, features)"""
shape = tensor.shape
assert len(shape) == 5
tensor = tf.reshape(tensor, (shape[0], shape[1], shape[2], -1,
self._t_enhance, shape[4]))
tensor = tf.math.reduce_sum(tensor, axis=4) / self._t_enhance
return tensor
def __call__(self, x1, x2):
"""Custom content loss calculated on re-coarsened low-res fields
Parameters
----------
x1 : tf.tensor
Synthetic high-res generator output, shape is either of these:
(n_obs, spatial_1, spatial_2, features)
(n_obs, spatial_1, spatial_2, temporal, features)
x2 : tf.tensor
True high resolution data, shape is either of these:
(n_obs, spatial_1, spatial_2, features)
(n_obs, spatial_1, spatial_2, temporal, features)
Returns
-------
tf.tensor
0D tensor loss value
"""
assert x1.shape == x2.shape
s_only = len(x1.shape) == 4
ex_loss = tf.constant(0, dtype=x1.dtype)
if self._ex_loss is not None:
ex_loss = self._ex_loss(x1, x2)
if self._s_enhance > 1 and s_only:
x1 = self._s_coarsen_4d_tensor(x1)
x2 = self._s_coarsen_4d_tensor(x2)
elif self._s_enhance > 1 and not s_only:
x1 = self._s_coarsen_5d_tensor(x1)
x2 = self._s_coarsen_5d_tensor(x2)
if self._t_enhance > 1 and self._t_method == 'average':
x1 = self._t_coarsen_avg(x1)
x2 = self._t_coarsen_avg(x2)
if self._t_enhance > 1 and self._t_method == 'subsample':
x1 = self._t_coarsen_sample(x1)
x2 = self._t_coarsen_sample(x2)
return self._tf_loss(x1, x2) + ex_loss