-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgenerator.py
More file actions
218 lines (200 loc) · 7.61 KB
/
Copy pathgenerator.py
File metadata and controls
218 lines (200 loc) · 7.61 KB
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
import torch
import torch.nn as nn
import torch.nn.functional as F
MAXLOG = 0.1
from torch.autograd import Variable
import collections
import numpy as np
from utils.model_config import GENERATORCONFIGS
class Generator(nn.Module):
def __init__(self, dataset='mnist', model='cnn', embedding=False, latent_layer_idx=-1):
super(Generator, self).__init__()
print("Dataset {}".format(dataset))
self.embedding = embedding
self.dataset = dataset
#self.model=model
self.latent_layer_idx = latent_layer_idx
self.hidden_dim, self.latent_dim, self.input_channel, self.n_class, self.noise_dim = GENERATORCONFIGS[dataset]
input_dim = self.noise_dim * 2 if self.embedding else self.noise_dim + self.n_class
self.fc_configs = [input_dim, self.hidden_dim]
self.init_loss_fn()
self.build_network()
def get_number_of_parameters(self):
pytorch_total_params=sum(p.numel() for p in self.parameters() if p.requires_grad)
return pytorch_total_params
def init_loss_fn(self):
self.crossentropy_loss=nn.NLLLoss(reduce=False) # same as above
self.diversity_loss = DiversityLoss(metric='l1')
self.dist_loss = nn.MSELoss()
def build_network(self):
if self.embedding:
self.embedding_layer = nn.Embedding(self.n_class, self.noise_dim)
### FC modules ####
self.fc_layers = nn.ModuleList()
for i in range(len(self.fc_configs) - 1):
input_dim, out_dim = self.fc_configs[i], self.fc_configs[i + 1]
print("Build layer {} X {}".format(input_dim, out_dim))
fc = nn.Linear(input_dim, out_dim)
bn = nn.BatchNorm1d(out_dim)
act = nn.ReLU()
self.fc_layers += [fc, bn, act]
### Representation layer
self.representation_layer = nn.Linear(self.fc_configs[-1], self.latent_dim)
print("Build last layer {} X {}".format(self.fc_configs[-1], self.latent_dim))
def forward(self, labels, latent_layer_idx=-1, verbose=True):
"""
G(Z|y) or G(X|y):
Generate either latent representation( latent_layer_idx < 0) or raw image (latent_layer_idx=0) conditional on labels.
:param labels:
:param latent_layer_idx:
if -1, generate latent representation of the last layer,
-2 for the 2nd to last layer, 0 for raw images.
:param verbose: also return the sampled Gaussian noise if verbose = True
:return: a dictionary of output information.
"""
result = {}
batch_size = labels.shape[0]
eps = torch.rand((batch_size, self.noise_dim)) # sampling from Gaussian
if verbose:
result['eps'] = eps
if self.embedding: # embedded dense vector
y_input = self.embedding_layer(labels)
else: # one-hot (sparse) vector
y_input = torch.FloatTensor(batch_size, self.n_class)
y_input.zero_()
#labels = labels.view
y_input.scatter_(1, labels.view(-1,1), 1)
z = torch.cat((eps, y_input), dim=1)
### FC layers
for layer in self.fc_layers:
z = layer(z)
z = self.representation_layer(z)
result['output'] = z
return result
@staticmethod
def normalize_images(layer):
"""
Normalize images into zero-mean and unit-variance.
"""
mean = layer.mean(dim=(2, 3), keepdim=True)
std = layer.view((layer.size(0), layer.size(1), -1)) \
.std(dim=2, keepdim=True).unsqueeze(3)
return (layer - mean) / std
#
# class Decoder(nn.Module):
# """
# Decoder for both unstructured and image datasets.
# """
# def __init__(self, dataset='mnist', latent_layer_idx=-1, n_layers=2, units=32):
# """
# Class initializer.
# """
# #in_features, out_targets, n_layers=2, units=32):
# super(Decoder, self).__init__()
# self.cv_configs, self.input_channel, self.n_class, self.scale, self.noise_dim = GENERATORCONFIGS[dataset]
# self.hidden_dim = self.scale * self.scale * self.cv_configs[0]
# self.latent_dim = self.cv_configs[0] * 2
# self.represent_dims = [self.hidden_dim, self.latent_dim]
# in_features = self.represent_dims[latent_layer_idx]
# out_targets = self.noise_dim
#
# # build layer structure
# layers = [nn.Linear(in_features, units),
# nn.ELU(),
# nn.BatchNorm1d(units)]
#
# for _ in range(n_layers):
# layers.extend([
# nn.Linear(units, units),
# nn.ELU(),
# nn.BatchNorm1d(units)])
#
# layers.append(nn.Linear(units, out_targets))
# self.layers = nn.Sequential(*layers)
#
# def forward(self, x):
# """
# Forward propagation.
# """
# out = x.view((x.size(0), -1))
# out = self.layers(out)
# return out
class DivLoss(nn.Module):
"""
Diversity loss for improving the performance.
"""
def __init__(self):
"""
Class initializer.
"""
super().__init__()
def forward2(self, noises, layer):
"""
Forward propagation.
"""
if len(layer.shape) > 2:
layer = layer.view((layer.size(0), -1))
chunk_size = layer.size(0) // 2
####### diversity loss ########
eps1, eps2=torch.split(noises, chunk_size, dim=0)
chunk1, chunk2=torch.split(layer, chunk_size, dim=0)
lz=torch.mean(torch.abs(chunk1 - chunk2)) / torch.mean(
torch.abs(eps1 - eps2))
eps=1 * 1e-5
diversity_loss=1 / (lz + eps)
return diversity_loss
def forward(self, noises, layer):
"""
Forward propagation.
"""
if len(layer.shape) > 2:
layer=layer.view((layer.size(0), -1))
chunk_size=layer.size(0) // 2
####### diversity loss ########
eps1, eps2=torch.split(noises, chunk_size, dim=0)
chunk1, chunk2=torch.split(layer, chunk_size, dim=0)
lz=torch.mean(torch.abs(chunk1 - chunk2)) / torch.mean(
torch.abs(eps1 - eps2))
eps=1 * 1e-5
diversity_loss=1 / (lz + eps)
return diversity_loss
class DiversityLoss(nn.Module):
"""
Diversity loss for improving the performance.
"""
def __init__(self, metric):
"""
Class initializer.
"""
super().__init__()
self.metric = metric
self.cosine = nn.CosineSimilarity(dim=2)
def compute_distance(self, tensor1, tensor2, metric):
"""
Compute the distance between two tensors.
"""
if metric == 'l1':
return torch.abs(tensor1 - tensor2).mean(dim=(2,))
elif metric == 'l2':
return torch.pow(tensor1 - tensor2, 2).mean(dim=(2,))
elif metric == 'cosine':
return 1 - self.cosine(tensor1, tensor2)
else:
raise ValueError(metric)
def pairwise_distance(self, tensor, how):
"""
Compute the pairwise distances between a Tensor's rows.
"""
n_data = tensor.size(0)
tensor1 = tensor.expand((n_data, n_data, tensor.size(1)))
tensor2 = tensor.unsqueeze(dim=1)
return self.compute_distance(tensor1, tensor2, how)
def forward(self, noises, layer):
"""
Forward propagation.
"""
if len(layer.shape) > 2:
layer = layer.view((layer.size(0), -1))
layer_dist = self.pairwise_distance(layer, how=self.metric)
noise_dist = self.pairwise_distance(noises, how='l2')
return torch.exp(torch.mean(-noise_dist * layer_dist))