| 1 |
|
| 2 |
r""" |
| 3 |
======================================== |
| 4 |
Wasserstein 2 Minibatch GAN with PyTorch |
| 5 |
======================================== |
| 6 |
|
| 7 |
In this example we train a Wasserstein GAN using Wasserstein 2 on minibatches |
| 8 |
as a distribution fitting term. |
| 9 |
|
| 10 |
We want to train a generator :math:`G_\theta` that generates realistic |
| 11 |
data from random noise drawn form a Gaussian :math:`\mu_n` distribution so |
| 12 |
that the data is indistinguishable from true data in the data distribution |
| 13 |
:math:`\mu_d`. To this end Wasserstein GAN [Arjovsky2017] aim at optimizing |
| 14 |
the parameters :math:`\theta` of the generator with the following |
| 15 |
optimization problem: |
| 16 |
|
| 17 |
.. math:: |
| 18 |
\min_{\theta} W(\mu_d,G_\theta\#\mu_n) |
| 19 |
|
| 20 |
|
| 21 |
In practice we do not have access to the full distribution :math:`\mu_d` but |
| 22 |
samples and we cannot compute the Wasserstein distance for large dataset. |
| 23 |
[Arjovsky2017] proposed to approximate the dual potential of Wasserstein 1 |
| 24 |
with a neural network recovering an optimization problem similar to GAN. |
| 25 |
In this example |
| 26 |
we will optimize the expectation of the Wasserstein distance over minibatches |
| 27 |
at each iterations as proposed in [Genevay2018]. Optimizing the Minibatches |
| 28 |
of the Wasserstein distance has been studied in [Fatras2019]. |
| 29 |
|
| 30 |
[Arjovsky2017] Arjovsky, M., Chintala, S., & Bottou, L. (2017, July). |
| 31 |
Wasserstein generative adversarial networks. In International conference |
| 32 |
on machine learning (pp. 214-223). PMLR. |
| 33 |
|
| 34 |
[Genevay2018] Genevay, Aude, Gabriel Peyré, and Marco Cuturi. "Learning generative models |
| 35 |
with sinkhorn divergences." International Conference on Artificial Intelligence |
| 36 |
and Statistics. PMLR, 2018. |
| 37 |
|
| 38 |
[Fatras2019] Fatras, K., Zine, Y., Flamary, R., Gribonval, R., & Courty, N. |
| 39 |
(2020, June). Learning with minibatch Wasserstein: asymptotic and gradient |
| 40 |
properties. In the 23nd International Conference on Artificial Intelligence |
| 41 |
and Statistics (Vol. 108). |
| 42 |
|
| 43 |
""" |
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
import numpy as np |
| 52 |
import matplotlib.pyplot as pl |
| 53 |
import matplotlib.animation as animation |
| 54 |
import torch |
| 55 |
from torch import nn |
| 56 |
import ot |
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
torch.manual_seed(1) |
| 64 |
sigma = 0.1 |
| 65 |
n_dims = 2 |
| 66 |
n_features = 2 |
| 67 |
|
| 68 |
|
| 69 |
def get_data(n_samples): |
| 70 |
c = torch.rand(size=(n_samples, 1)) |
| 71 |
angle = c * 2 * np.pi |
| 72 |
x = torch.cat((torch.cos(angle), torch.sin(angle)), 1) |
| 73 |
x += torch.randn(n_samples, 2) * sigma |
| 74 |
return x |
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
x = get_data(500) |
| 83 |
pl.figure(1) |
| 84 |
pl.scatter(x[:, 0], x[:, 1], label="Data samples from $\mu_d$", alpha=0.5) |
| 85 |
pl.title("Data distribution") |
| 86 |
pl.legend() |
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
class Generator(torch.nn.Module): |
| 96 |
def __init__(self): |
| 97 |
super(Generator, self).__init__() |
| 98 |
self.fc1 = nn.Linear(n_features, 200) |
| 99 |
self.fc2 = nn.Linear(200, 500) |
| 100 |
self.fc3 = nn.Linear(500, n_dims) |
| 101 |
self.relu = torch.nn.ReLU() |
| 102 |
|
| 103 |
def forward(self, x): |
| 104 |
output = self.fc1(x) |
| 105 |
output = self.relu(output) |
| 106 |
output = self.fc2(output) |
| 107 |
output = self.relu(output) |
| 108 |
output = self.fc3(output) |
| 109 |
return output |
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
G = Generator() |
| 118 |
optimizer = torch.optim.RMSprop(G.parameters(), lr=0.00019, eps=1e-5) |
| 119 |
|
| 120 |
|
| 121 |
n_iter = 200 |
| 122 |
size_batch = 500 |
| 123 |
|
| 124 |
|
| 125 |
n_visu = 100 |
| 126 |
xnvisu = torch.randn(n_visu, n_features) |
| 127 |
xvisu = torch.zeros(n_iter, n_visu, n_dims) |
| 128 |
|
| 129 |
ab = torch.ones(size_batch) / size_batch |
| 130 |
losses = [] |
| 131 |
|
| 132 |
|
| 133 |
for i in range(n_iter): |
| 134 |
|
| 135 |
xn = torch.randn(size_batch, n_features) |
| 136 |
|
| 137 |
|
| 138 |
xd = get_data(size_batch) |
| 139 |
|
| 140 |
|
| 141 |
xvisu[i, :, :] = G(xnvisu).detach() |
| 142 |
|
| 143 |
|
| 144 |
xg = G(xn) |
| 145 |
M = ot.dist(xg, xd) |
| 146 |
|
| 147 |
loss = ot.emd2(ab, ab, M) |
| 148 |
losses.append(float(loss.detach())) |
| 149 |
|
| 150 |
if i % 10 == 0: |
| 151 |
print("Iter: {:3d}, loss={}".format(i, losses[-1])) |
| 152 |
|
| 153 |
loss.backward() |
| 154 |
optimizer.step() |
| 155 |
optimizer.zero_grad() |
| 156 |
|
| 157 |
del M |
| 158 |
|
| 159 |
pl.figure(2) |
| 160 |
pl.semilogy(losses) |
| 161 |
pl.grid() |
| 162 |
pl.title("Wasserstein distance") |
| 163 |
pl.xlabel("Iterations") |
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
|
| 171 |
pl.figure(3, (10, 10)) |
| 172 |
|
| 173 |
ivisu = [0, 10, 25, 50, 75, 125, 15, 175, 199] |
| 174 |
|
| 175 |
for i in range(9): |
| 176 |
pl.subplot(3, 3, i + 1) |
| 177 |
pl.scatter(xd[:, 0], xd[:, 1], label="Data samples from $\mu_d$", alpha=0.1) |
| 178 |
pl.scatter( |
| 179 |
xvisu[ivisu[i], :, 0], |
| 180 |
xvisu[ivisu[i], :, 1], |
| 181 |
label="Data samples from $G\#\mu_n$", |
| 182 |
alpha=0.5, |
| 183 |
) |
| 184 |
pl.xticks(()) |
| 185 |
pl.yticks(()) |
| 186 |
pl.title("Iter. {}".format(ivisu[i])) |
| 187 |
if i == 0: |
| 188 |
pl.legend() |
| 189 |
|
| 190 |
|
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
pl.figure(4, (8, 8)) |
| 195 |
|
| 196 |
|
| 197 |
def _update_plot(i): |
| 198 |
pl.clf() |
| 199 |
pl.scatter(xd[:, 0], xd[:, 1], label="Data samples from $\mu_d$", alpha=0.1) |
| 200 |
pl.scatter( |
| 201 |
xvisu[i, :, 0], xvisu[i, :, 1], label="Data samples from $G\#\mu_n$", alpha=0.5 |
| 202 |
) |
| 203 |
pl.xticks(()) |
| 204 |
pl.yticks(()) |
| 205 |
pl.xlim((-1.5, 1.5)) |
| 206 |
pl.ylim((-1.5, 1.5)) |
| 207 |
pl.title("Iter. {}".format(i)) |
| 208 |
return 1 |
| 209 |
|
| 210 |
|
| 211 |
i = 0 |
| 212 |
pl.scatter(xd[:, 0], xd[:, 1], label="Data samples from $\mu_d$", alpha=0.1) |
| 213 |
pl.scatter( |
| 214 |
xvisu[i, :, 0], xvisu[i, :, 1], label="Data samples from $G\#\mu_n$", alpha=0.5 |
| 215 |
) |
| 216 |
pl.xticks(()) |
| 217 |
pl.yticks(()) |
| 218 |
pl.xlim((-1.5, 1.5)) |
| 219 |
pl.ylim((-1.5, 1.5)) |
| 220 |
pl.title("Iter. {}".format(ivisu[i])) |
| 221 |
|
| 222 |
|
| 223 |
ani = animation.FuncAnimation( |
| 224 |
pl.gcf(), _update_plot, n_iter, interval=100, repeat_delay=2000 |
| 225 |
) |
| 226 |
|
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
size_batch = 500 |
| 232 |
xd = get_data(size_batch) |
| 233 |
xn = torch.randn(size_batch, 2) |
| 234 |
x = G(xn).detach().numpy() |
| 235 |
|
| 236 |
pl.figure(5) |
| 237 |
pl.scatter(xd[:, 0], xd[:, 1], label="Data samples from $\mu_d$", alpha=0.5) |
| 238 |
pl.scatter(x[:, 0], x[:, 1], label="Data samples from $G\#\mu_n$", alpha=0.5) |
| 239 |
pl.title("Sources and Target distributions") |
| 240 |
pl.legend() |