-
Notifications
You must be signed in to change notification settings - Fork 47
/
visualize.py
executable file
·207 lines (183 loc) · 8.9 KB
/
visualize.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
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
from abstract_network import *
import os
import scipy.misc as misc
class Visualizer:
def __init__(self, network):
plt.ion()
plt.show()
self.fig = None
self.network = network
self.name = "default"
self.save_epoch = 0
self.array_save_epoch = 0
def visualize(self, **args):
pass
def fig_to_file(self, fig=None):
if fig is None:
fig = self.fig
img_folder = "models/" + self.network.name + "/" + self.name
if not os.path.isdir(img_folder):
os.makedirs(img_folder)
fig_name = "current.png"
fig.savefig(os.path.join(img_folder, fig_name))
fig_name = "epoch%d" % self.save_epoch + ".png"
fig.savefig(os.path.join(img_folder, fig_name))
self.save_epoch += 1
def arr_to_file(self, arr):
img_folder = "models/" + self.network.name + "/" + self.name
if not os.path.isdir(img_folder):
os.makedirs(img_folder)
if arr.shape[-1] == 1:
misc.imsave(os.path.join(img_folder, 'current.png'), arr[:, :, 0])
misc.imsave(os.path.join(img_folder, 'epoch%d.png' % self.save_epoch), arr[:, :, 0])
else:
misc.imsave(os.path.join(img_folder, 'current.png'), arr)
misc.imsave(os.path.join(img_folder, 'epoch%d.png' % self.save_epoch), arr)
self.save_epoch += 1
class ConditionalSampleVisualizer(Visualizer):
""" sess should be the session where the visualized network run,
visualized_variable should be a [batch_size, *] tensor, and title is the title of plotted graph """
def __init__(self, network, dataset):
Visualizer.__init__(self, network)
self.dataset = dataset
self.name = "conditional_samples"
def visualize(self, layers, num_rows=4, use_gui=False):
if use_gui and self.fig is None:
self.fig, self.ax = plt.subplots(1, len(layers))
latent_code = self.network.random_latent_code()
canvas_list = []
for i, layer in enumerate(layers):
samples = np.zeros([num_rows*num_rows]+self.dataset.data_dims)
samples_ptr = 0
while samples_ptr < num_rows * num_rows:
# Generate a few samples each time. Too many samples with distribution on latent code
# different from training time breaks batch norm
new_samples, _ = self.network.generate_conditional_samples(layer, latent_code)
next_ptr = samples_ptr + new_samples.shape[0]
if next_ptr > num_rows * num_rows:
next_ptr = num_rows * num_rows
samples[samples_ptr:next_ptr] = new_samples[0:next_ptr-samples_ptr]
samples_ptr = next_ptr
# Plot the samples in a grid
if samples is not None:
samples = self.dataset.display(samples)
width = samples.shape[1]
height = samples.shape[2]
channel = samples.shape[3]
canvas = np.zeros((width * num_rows, height * num_rows, channel))
for img_index1 in range(num_rows):
for img_index2 in range(num_rows):
canvas[img_index1 * width:(img_index1 + 1) * width,
img_index2 * height:(img_index2 + 1) * height, :] = \
samples[img_index1 * num_rows + img_index2, :, :, :]
if use_gui:
self.ax[i].cla()
if channel == 1:
self.ax[i].imshow(canvas[:, :, 0], cmap=plt.get_cmap('Greys'))
else:
self.ax[i].imshow(canvas)
self.ax[i].xaxis.set_visible(False)
self.ax[i].yaxis.set_visible(False)
if i != 0:
if canvas.shape[-1] == 1:
canvas_list.append(np.zeros((width * num_rows, 20, channel)))
else:
canvas_list.append(np.ones((width * num_rows, 20, channel)))
canvas_list.append(canvas)
else:
print("Warning: no samples generated during visualization")
# np.save('samples', canvas)
canvas = np.concatenate(canvas_list, axis=1)
self.arr_to_file(canvas)
if use_gui:
self.fig.suptitle('Conditional Samples for %s' % self.network.name)
plt.draw()
plt.pause(0.01)
class SampleVisualizer(Visualizer):
""" sess should be the session where the visualized network run,
visualized_variable should be a [batch_size, *] tensor, and title is the title of plotted graph """
def __init__(self, network, dataset):
Visualizer.__init__(self, network)
# self.fig.suptitle("Samples generated by " + str(network.name))
self.dataset = dataset
self.name = "samples"
def visualize(self, num_rows=10, use_gui=False):
if use_gui and self.fig is None:
self.fig, self.ax = plt.subplots()
samples = self.network.generate_samples()
if samples is not None:
samples = self.dataset.display(samples)
width = samples.shape[1]
height = samples.shape[2]
channel = samples.shape[3]
canvas = np.zeros((width * num_rows, height * num_rows, channel))
for img_index1 in range(num_rows):
for img_index2 in range(num_rows):
canvas[img_index1*width:(img_index1+1)*width, img_index2*height:(img_index2+1)*height, :] = \
samples[img_index1*num_rows+img_index2, :, :, :]
self.arr_to_file(canvas)
if use_gui:
self.ax.cla()
if channel == 1:
self.ax.imshow(canvas[:, :, 0], cmap=plt.get_cmap('Greys'))
else:
self.ax.imshow(canvas)
self.ax.xaxis.set_visible(False)
self.ax.yaxis.set_visible(False)
self.fig.suptitle('Samples for %s' % self.network.name)
plt.draw()
plt.pause(0.01)
class ManifoldSampleVisualizer(Visualizer):
def __init__(self, network, dataset):
Visualizer.__init__(self, network)
# self.fig.suptitle("Samples generated by " + str(network.name))
self.dataset = dataset
self.name = "manifold_samples"
def visualize(self, layers, num_rows=4, use_gui=False):
if use_gui and self.fig is None:
self.fig, self.ax = plt.subplots(1, len(layers))
canvas_list = []
for i, layer in enumerate(layers):
samples = np.zeros([num_rows*num_rows]+self.dataset.data_dims)
samples_ptr = 0
latent_code_x = np.tile(np.reshape(np.linspace(-2.0, 2.0, num=num_rows), (1, num_rows)), (num_rows, 1))
latent_code_y = latent_code_x.transpose()
latent_code = np.reshape(np.stack([latent_code_x, latent_code_y], axis=-1), (-1, 2))
while samples_ptr < num_rows * num_rows:
new_samples = self.network.generate_manifold_samples(layer, latent_code)
latent_code = latent_code[new_samples.shape[0]:]
next_ptr = samples_ptr + new_samples.shape[0]
if next_ptr > num_rows * num_rows:
next_ptr = num_rows * num_rows
samples[samples_ptr:next_ptr] = new_samples[0:next_ptr-samples_ptr]
samples_ptr = next_ptr
if samples is not None:
width = samples.shape[1]
height = samples.shape[2]
channel = samples.shape[3]
canvas = np.zeros((width * num_rows, height * num_rows, channel))
for img_index1 in range(num_rows):
for img_index2 in range(num_rows):
canvas[img_index1 * width:(img_index1 + 1) * width,
img_index2 * height:(img_index2 + 1) * height, :] = \
self.dataset.display(samples[img_index1 * num_rows + img_index2, :, :, :])
if use_gui:
self.ax[i].cla()
if channel == 1:
self.ax[i].imshow(canvas[:, :, 0], cmap=plt.get_cmap('Greys'))
else:
self.ax[i].imshow(canvas)
self.ax[i].xaxis.set_visible(False)
self.ax[i].yaxis.set_visible(False)
if i != 0:
if canvas.shape[-1] == 1:
canvas_list.append(np.zeros((width * num_rows, 20, channel)))
else:
canvas_list.append(np.ones((width * num_rows, 20, channel)))
canvas_list.append(canvas)
canvas = np.concatenate(canvas_list, axis=1)
self.arr_to_file(canvas)
if use_gui:
self.fig.suptitle('Manifold Samples for %s' % self.network.name)
plt.draw()
plt.pause(0.01)