-
Notifications
You must be signed in to change notification settings - Fork 1
/
wgan.py
142 lines (124 loc) · 4.07 KB
/
wgan.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
# -*- coding: utf-8 -*-
"""WGAN.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1PLETyU5HnnD2776Xgp7NON6VU5DuMUlT
"""
import torch
import torch.nn as nn
import torch.optim as optim
from matplotlib import pyplot as plt
import numpy as np
from torchvision import transforms
from torchvision.datasets import MNIST
from torchvision.utils import make_grid
from torch.utils.data import DataLoader
import imageio
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5,),(0.5,))
])
to_image = transforms.ToPILImage()
trainset = MNIST(root='./data/', train=True, download=True, transform=transform)
trainloader = DataLoader(trainset, batch_size=64, shuffle=True)
device = 'cuda'
class Generator(nn.Module):
def __init__(self):
super(Generator, self).__init__()
self.n_features = 100
self.n_out = 784
self.model = nn.Sequential(
nn.Linear(self.n_features, 256),
nn.LeakyReLU(0.2),
nn.Linear(256, 512),
nn.LeakyReLU(0.2),
nn.Linear(512, 1024),
nn.LeakyReLU(0.2),
nn.Linear(1024, self.n_out),
nn.Tanh()
)
def forward(self, x):
x = self.model(x)
x = x.view(-1, 1, 28, 28)
return x
class Critic(nn.Module):
def __init__(self):
super(Critic, self).__init__()
self.n_in = 784
self.n_out = 1
self.model = nn.Sequential(
nn.Linear(self.n_in, 1024),
nn.LeakyReLU(0.2),
nn.Dropout(0.3),
nn.Linear(1024, 512),
nn.LeakyReLU(0.2),
nn.Dropout(0.3),
nn.Linear(512, 256),
nn.LeakyReLU(0.2),
nn.Dropout(0.3),
nn.Linear(256, self.n_out)
)
def forward(self, x):
x = x.view(-1, 784)
x = self.model(x)
return x
generator = Generator()
critic = Critic()
generator.to(device)
critic.to(device)
alpha = 5e-5
g_optim = optim.RMSprop(generator.parameters(), lr=alpha)
c_optim = optim.RMSprop(critic.parameters(), lr=alpha)
g_losses = []
c_losses = []
images = []
def noise(n, n_features=100):
return torch.randn(n, n_features).to(device)
def train_critic(optimizer, real_data, fake_data, c=0.01):
optimizer.zero_grad()
error_real = critic(real_data).mean()
error_fake = critic(fake_data).mean()
total_error = -(error_real - error_fake)
total_error.backward()
optimizer.step()
for p in critic.parameters():
p.data.clamp_(-c, c)
return -total_error
def train_generator(optimizer, fake_data):
optimizer.zero_grad()
error = -critic(fake_data).mean()
error.backward()
optimizer.step()
return error
num_epochs = 250
n_critic = 5
test_noise = noise(64)
generator.train()
critic.train()
for epoch in range(num_epochs):
g_error = 0.0
c_error = 0.0
for i, data in enumerate(trainloader):
imgs, _ = data
n = len(imgs)
fake_data = generator(noise(n)).detach()
real_data = imgs.to(device)
c_error += train_critic(c_optim, real_data, fake_data)
if (i+1)%n_critic==0:
fake_data = generator(noise(n))
g_error += train_generator(g_optim, fake_data)
if epoch%5==0:
img = generator(test_noise).cpu().detach()
img = make_grid(img)
images.append(to_image(img))
g_losses.append(g_error)
c_losses.append(c_error)
plt.clf()
plt.plot(g_losses, label='Generator Losses')
plt.plot(c_losses, label='Critic Losses')
plt.legend()
plt.savefig('loss.png')
imageio.mimsave('progress.gif', [np.array(i) for i in images])
print('Epoch {}: G_loss: {:.4f} C_loss: {:.4f}'.format(epoch, g_error, c_error))
print('Training Finished')
torch.save(generator.state_dict(), 'mnist_generator.pth')