-
Notifications
You must be signed in to change notification settings - Fork 558
/
losses.py
52 lines (38 loc) · 1.92 KB
/
losses.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
# Copyright 2019-2020 Stanislav Pidhorskyi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import torch
import torch.nn.functional as F
__all__ = ['kl', 'reconstruction', 'discriminator_logistic_simple_gp',
'discriminator_gradient_penalty', 'generator_logistic_non_saturating']
def kl(mu, log_var):
return -0.5 * torch.mean(torch.mean(1 + log_var - mu.pow(2) - log_var.exp(), 1))
def reconstruction(recon_x, x, lod=None):
return torch.mean((recon_x - x)**2)
def discriminator_logistic_simple_gp(d_result_fake, d_result_real, reals, r1_gamma=10.0):
loss = (F.softplus(d_result_fake) + F.softplus(-d_result_real))
if r1_gamma != 0.0:
real_loss = d_result_real.sum()
real_grads = torch.autograd.grad(real_loss, reals, create_graph=True, retain_graph=True)[0]
r1_penalty = torch.sum(real_grads.pow(2.0), dim=[1, 2, 3])
loss = loss + r1_penalty * (r1_gamma * 0.5)
return loss.mean()
def discriminator_gradient_penalty(d_result_real, reals, r1_gamma=10.0):
real_loss = d_result_real.sum()
real_grads = torch.autograd.grad(real_loss, reals, create_graph=True, retain_graph=True)[0]
r1_penalty = torch.sum(real_grads.pow(2.0), dim=[1, 2, 3])
loss = r1_penalty * (r1_gamma * 0.5)
return loss.mean()
def generator_logistic_non_saturating(d_result_fake):
return F.softplus(-d_result_fake).mean()