MCPcopy Create free account
hub / github.com/KeepTryingTo/Pytorch-GAN / gradient_penalty

Function gradient_penalty

StyleGAN/utils.py:34–54  ·  view source on GitHub ↗
(critic, real, fake, alpha, train_step, device="cpu")

Source from the content-addressed store, hash-verified

32
33#这里沿用了GP-GAN中的公式
34def gradient_penalty(critic, real, fake, alpha, train_step, device="cpu"):
35 BATCH_SIZE, C, H, W = real.shape
36 beta = torch.rand((BATCH_SIZE, 1, 1, 1)).repeat(1, C, H, W).to(device)
37 interpolated_images = real * beta + fake.detach() * (1 - beta)
38 interpolated_images.requires_grad_(True)
39
40 # Calculate critic scores
41 mixed_scores = critic(interpolated_images, alpha, train_step)
42
43 # Take the gradient of the scores with respect to the images
44 gradient = torch.autograd.grad(
45 inputs=interpolated_images,
46 outputs=mixed_scores,
47 grad_outputs=torch.ones_like(mixed_scores),
48 create_graph=True,
49 retain_graph=True,
50 )[0]
51 gradient = gradient.view(gradient.shape[0], -1)
52 gradient_norm = gradient.norm(2, dim=1)
53 gradient_penalty = torch.mean((gradient_norm - 1) ** 2)
54 return gradient_penalty
55
56
57#保存模型,通常的做法

Callers 1

train_fnFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected