-
Notifications
You must be signed in to change notification settings - Fork 5
/
utils_plot.py
402 lines (336 loc) · 15 KB
/
utils_plot.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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import scipy.io as sio
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
# display a 2D plot of the datapoints in the latent space
def plot_latent_space(encoder, data, ax,
batch_size=512, dims=(0,1),
colorbar=False, use_pca=False):
x_test, y_test = data
z_mean, z_log_var = encoder.predict(x_test, batch_size=batch_size)
if use_pca:
scaler = StandardScaler()
pca = PCA(n_components=None, svd_solver='randomized')
zs = scaler.fit_transform(z_mean)
z_pca = pca.fit_transform(zs)
zd_pca = pd.DataFrame(z_pca, columns=[f'PC_{i}' for i in range(z_pca.shape[1])])
zd_pca['target'] = y_test
sc = ax.scatter(zd_pca[:, dims[0]], zd_pca[:, dims[1]], c=zd_pca['target'], alpha=0.75)
else:
zd = pd.DataFrame(z_mean, columns=[f'Z_{i}' for i in range(z_mean.shape[1])])
zd['target'] = y_test
sc = ax.scatter(zd.iloc[:, dims[0]], zd.iloc[:, dims[1]], c=zd['target'], alpha=0.75)
if colorbar:
plt.colorbar(sc, ax=ax)
xname = 'pc' if use_pca else 'z'
ax.set_xlabel("{}[{}]".format(xname, dims[0]))
ax.set_ylabel("{}[{}]".format(xname, dims[1]))
ax.set_title(dims)
# display a grid of plots for all combinations of latent dimensions
def plot_latent_pairs(encoder, data,
batch_size=512, n_pca=False, n_dim=False, height=2.5, nlvl=5, plot_kws={}):
x_test, y_test = data
z_mean, z_log_var = encoder.predict(x_test, batch_size=batch_size)
if n_pca:
scaler = StandardScaler()
pca = PCA(n_components=None, svd_solver='randomized')
zs = scaler.fit_transform(z_mean)
z_pca = pca.fit_transform(zs)
zd_pca = pd.DataFrame(z_pca, columns=[f'Z_PC{i}' for i in range(z_pca.shape[1])])
zd_pca['hue'] = pd.qcut(y_test.astype(float), nlvl, labels=False)
sns.pairplot(data=zd_pca, vars=zd_pca.columns[:n_pca], hue='hue',
palette=sns.color_palette('BrBG', nlvl),
height=height, plot_kws=plot_kws)
elif n_dim:
zd = pd.DataFrame(z_mean, columns=[f'Z{i}' for i in range(z_mean.shape[1])])
zd['hue'] = pd.qcut(y_test.astype(float), nlvl, labels=False)
sns.pairplot(data=zd, vars=zd.columns[:n_dim], hue='hue',
palette=sns.color_palette('GnBu_d', nlvl),
height=height, plot_kws=plot_kws)
else:
print('Pass n_dim or n_pca!!')
# display a grid of plots for all combinations of latent dimensions
def plot_xcorr(encoder, data, ax,
batch_size=512, pca=False,
labels=False):
x_test, y_test = data
z_mean, z_log_var = encoder.predict(x_test, batch_size=batch_size)
cmap = sns.diverging_palette(220, 10, as_cmap=True)
if pca:
scaler = StandardScaler()
pca = PCA(n_components=None, svd_solver='randomized')
zs = scaler.fit_transform(z_mean)
z_pca = pca.fit_transform(zs)
zd_pca = pd.DataFrame(z_pca, columns=[f'PC{i}' for i in range(z_pca.shape[1])])
x = zd_pca
else:
zd = pd.DataFrame(z_mean, columns=[f'Z{i}' for i in range(z_mean.shape[1])])
x = zd
corr = pd.concat([x, y_test], axis=1, keys=['df1', 'df2']).corr().loc['df1', 'df2']
sns.heatmap(data=corr, cmap=cmap, vmin=-0.9, vmax=0.9,
center=0, square=True, annot=labels, fmt='.2f',
linewidths=.5, cbar_kws={"shrink": .5}, ax=ax)
ax.set_ylim(len(corr)+0.5, -0.5)
return corr
# display a grid of plots for all combinations of latent dimensions
def plot_xcorr_cvae(encoder, data, ax,
batch_size=512, pca=False,
labels=False):
x_test, y_test = data
x_input = np.concatenate((x_test, y_test[['azimuth_norm', 'elevation_norm']]), axis=1)
z_mean, z_log_var = encoder.predict(x_input, batch_size=batch_size)
cmap = sns.diverging_palette(220, 10, as_cmap=True)
if pca:
scaler = StandardScaler()
pca = PCA(n_components=None, svd_solver='randomized')
zs = scaler.fit_transform(z_mean)
z_pca = pca.fit_transform(zs)
zd_pca = pd.DataFrame(z_pca, columns=[f'PC{i}' for i in range(z_pca.shape[1])])
x = zd_pca
else:
zd = pd.DataFrame(z_mean, columns=[f'Z{i}' for i in range(z_mean.shape[1])])
x = zd
corr = pd.concat([x, y_test], axis=1, keys=['df1', 'df2']).corr().loc['df1', 'df2']
sns.heatmap(data=corr, cmap=cmap, vmin=-0.9, vmax=0.9,
center=0, square=True, annot=labels, fmt='.2f',
linewidths=.5, cbar_kws={"shrink": .5}, ax=ax)
ax.set_ylim(len(corr)+0.5, -0.5)
return corr
# display reconstructed images
def plot_reconstructions(encoder, decoder, data, axs, batch_size=512, freq_loss=False, side='h'):
x_test, y_test = data
img_size = x_test.shape[1:-1]
n_imgs = len(axs.flatten())
z_mean, z_log_var = encoder.predict(x_test[:n_imgs], batch_size=batch_size)
if freq_loss:
z_mean = np.concatenate([z_mean, y_test[:n_imgs,np.newaxis]], axis=-1)
for i, ax in enumerate(axs.flatten()):
n = int(float(len(x_test) / len(axs.flatten()) * i))
# reconstruct
z_sample = z_mean[np.newaxis, i]
x_decoded = decoder.predict(z_sample)
# generate image
img_input = x_test[i,...,0]
img_decoded = x_decoded[0].reshape(img_size)
img = np.hstack((img_input, img_decoded)) if side=='h' else np.vstack((img_input, img_decoded))
# show in plot
im = ax.imshow(img, cmap='Greys_r')
ax.axis('off')
# display reconstructed hrtfs
def plot_reconstruction_hrtfs(encoder, decoder, data, axs, batch_size=512, elevation=0):
x_test, y_test = data
img_size = x_test.shape[1:-1]
configs = sio.loadmat('./data/hutubs_hrtf/configs.mat')
freqs = configs['f'][0]
elevs = configs['elevations'][0]
# elevation to index
el_index = np.where(elevs == elevation)[0][0]
step = len(x_test) // len(axs.flatten())
z_mean, z_log_var = encoder.predict(x_test[::step], batch_size=batch_size)
for i, ax in enumerate(axs.flatten()):
n = i * step
# reconstruct
z_sample = z_mean[np.newaxis, i]
x_decoded = decoder.predict(z_sample)
# show in plot
hrtf_true = x_test[n,el_index,:,0]
hrtf_pred = x_decoded[0,el_index,:,0]
line_true, = ax.plot(freqs, hrtf_true, label='true')
line_pred, = ax.plot(freqs, hrtf_pred, label='pred')
ax.legend(handles=[line_true, line_pred])
ax.set_title('#{:02}{} - ({:.0f}° ; {:.0f}°)'.format(
y_test['id'].iloc[n],
y_test['ear'].iloc[n][0].upper(),
y_test['azimuth'].iloc[n],
elevation))
ax.set_ylim([-60, 20])
ax.set_yticks(np.arange(-60, 21, 20))
ax.yaxis.grid()
#ax.axis('off')
# display reconstructed hrtfs
def plot_reconstructions_3d(encoder, decoder, data, axs, batch_size=512):
x_test, y_test = data
img_size = x_test.shape[1:-1]
configs = sio.loadmat('./data/hutubs_hrtf/configs.mat')
freqs = configs['f'][0]
elevs = configs['elevations'][0]
step = len(x_test) // len(axs.flatten())
z_mean, z_log_var = encoder.predict(x_test[::step], batch_size=batch_size)
for i, ax in enumerate(axs.flatten()):
n = i * step
# reconstruct
z_sample = z_mean[np.newaxis, i]
x_decoded = decoder.predict(z_sample)
# show in plot
hrtf_true = x_test[n,3,3,:]
hrtf_pred = x_decoded[0,3,3,:]
line_true, = ax.plot(freqs, hrtf_true, label='true')
line_pred, = ax.plot(freqs, hrtf_pred, label='pred')
ax.legend(handles=[line_true, line_pred])
ax.set_title('#{:02}{} ({:.0f}° ; {:.0f}°)'.format(
y_test['id'].iloc[n],
y_test['ear'].iloc[n][0].upper(),
y_test['azimuth'].iloc[n],
y_test['elevation'].iloc[n]))
ax.set_ylim([-60, 20])
ax.set_xlim([0, 18000])
ax.set_yticks(np.arange(-60, 21, 20))
ax.yaxis.grid()
#ax.axis('off')
# display reconstructed hrtfs from one-hot encoding
def plot_reconstructions_3d_oh(encoder, decoder, data, axs, batch_size=512):
x_test, y_test = data
img_size = x_test.shape[1:-1]
configs = sio.loadmat('./data/hutubs_hrtf/configs.mat')
freqs = configs['f'][0]
elevs = configs['elevations'][0]
step = len(x_test) // len(axs.flatten())
z_mean, z_log_var = encoder.predict(x_test[::step], batch_size=batch_size)
for i, ax in enumerate(axs.flatten()):
n = i * step
# reconstruct
z_sample = z_mean[np.newaxis, i]
x_decoded = decoder.predict(z_sample)
# show in plot
hrtf_true = x_test[n,3,3,:]
vmin = -60
vmax = 20
hrtf_pred = (np.argmax(x_decoded[0], axis=1)/255*(vmax-vmin))+vmin
line_true, = ax.plot(freqs, hrtf_true, label='true')
line_pred, = ax.plot(freqs, hrtf_pred, label='pred')
ax.legend(handles=[line_true, line_pred])
ax.set_title('#{:02}{} ({:.0f}° ; {:.0f}°)'.format(
y_test['id'].iloc[n],
y_test['ear'].iloc[n][0].upper(),
y_test['azimuth'].iloc[n],
y_test['elevation'].iloc[n]))
#ax.set_ylim([-60, 20])
ax.set_xlim([0, 18000])
#ax.set_yticks(np.arange(-60, 21, 20))
ax.yaxis.grid()
#ax.axis('off')
# display reconstructed hrtfs (chen et al. 2019 paper)
def plot_reconstructions_chen2019(encoder, decoder, data, axs, batch_size=512, x_train_mean=0, x_train_std=1, show_axes=False):
x_test, y_test = data
step = len(x_test) // len(axs.flatten())
x = x_test[::step]
y = y_test.iloc[::step]
# load configs
configs = sio.loadmat('./data/hutubs_hrtf/configs.mat')
freqs = configs['f'][0]
# encode data
z_mean, z_log_var = encoder.predict(x, batch_size=batch_size)
for i, ax in enumerate(axs.flatten()):
# reconstruct
z_sample = np.concatenate((z_mean[i], y[['azimuth_norm', 'elevation_norm']].iloc[i]))
x_decoded = decoder.predict(z_sample[np.newaxis,:])
# show in plot
hrtf_true = (x[i] * x_train_std) + x_train_mean
hrtf_pred = (x_decoded[0] * x_train_std) + x_train_mean
line_true, = ax.plot(freqs, hrtf_true, label='true')
line_pred, = ax.plot(freqs, hrtf_pred, label='pred')
ax.set_title('#{:02}{} ({:.0f}° ; {:.0f}°)'.format(
y['id'].iloc[i],
y['ear'].iloc[i][0].upper(),
y['azimuth'].iloc[i],
y['elevation'].iloc[i]))
ax.set_ylim([-40, 20])
ax.set_xlim([0, 18000])
if show_axes:
ax.legend(handles=[line_true, line_pred])
ax.set_yticks(np.arange(-40, 21, 10))
ax.yaxis.grid()
else:
ax.axis('off')
# display reconstructed hrtfs (CVAE)
def plot_reconstructions_cvae(encoder, decoder, data, axs, batch_size=512, x_train_mean=0, x_train_std=1, show_axes=False):
x_test, y_test = data
step = len(x_test) // len(axs.flatten())
x = x_test[::step]
y = y_test.iloc[::step]
print(x.shape, y[['azimuth_norm', 'elevation_norm']].shape)
x_input = np.concatenate((x, y[['azimuth_norm', 'elevation_norm']]), axis=1)
print(x_input.shape)
# load configs
configs = sio.loadmat('./data/hutubs_hrtf/configs.mat')
freqs = configs['f'][0]
# encode data
z_mean, z_log_var = encoder.predict(x_input, batch_size=batch_size)
for i, ax in enumerate(axs.flatten()):
# reconstruct
z_sample = np.concatenate((z_mean[i], y[['azimuth_norm', 'elevation_norm']].iloc[i]))
x_decoded = decoder.predict(z_sample[np.newaxis,:])
# show in plot
hrtf_true = (x[i] * x_train_std) + x_train_mean
hrtf_pred = (x_decoded[0] * x_train_std) + x_train_mean
line_true, = ax.plot(freqs, hrtf_true, label='true')
line_pred, = ax.plot(freqs, hrtf_pred, label='pred')
ax.set_title('#{:02}{} ({:.0f}° ; {:.0f}°)'.format(
y['id'].iloc[i],
y['ear'].iloc[i][0].upper(),
y['azimuth'].iloc[i],
y['elevation'].iloc[i]))
ax.set_ylim([-40, 20])
ax.set_xlim([0, 18000])
if show_axes:
ax.legend(handles=[line_true, line_pred])
ax.set_yticks(np.arange(-40, 21, 10))
ax.yaxis.grid()
else:
ax.axis('off')
## OLD FUNCTION (TODO put sandom sampling into new function)
def plot_results(models,
data,
batch_size=128,
digit_size=100,
figsize=(12, 4),
grid_range=(-1, 1),
n=10,
ndims=2,
dims=[0,1],
model_name="vae_mnist"):
reconstruction = False
fig, ax = plt.subplots(1, 2, figsize=figsize)
encoder, decoder = models
x_test, y_test = data
# display a 2D plot of the digit classes in the latent space
z_mean, z_log_var, z = encoder.predict(x_test, batch_size=batch_size)
sc = ax[0].scatter(z_mean[:, dims[0]], z_mean[:, dims[1]], c=y_test, alpha=0.75)
plt.colorbar(sc, ax=ax)
ax[0].set_xlabel("z[{}]".format(dims[0]))
ax[0].set_ylabel("z[{}]".format(dims[1]))
# display a 30x30 2D manifold of digits
figure = np.zeros((digit_size * n, digit_size * n))
# linearly spaced coordinates corresponding to the 2D plot
# of digit classes in the latent space
grid_x = np.linspace(*grid_range, n)
grid_y = np.linspace(*grid_range, n)[::-1]
for i, yi in enumerate(grid_y):
for j, xi in enumerate(grid_x):
if not reconstruction:
z_sample = np.zeros((1, ndims))
z_sample[:, dims[0]] = xi
z_sample[:, dims[1]] = yi
else:
z_sample = z_mean[np.newaxis, i*n+j]
x_decoded = decoder.predict(z_sample)
digit = x_decoded[0].reshape(digit_size, digit_size)
figure[i * digit_size: (i + 1) * digit_size,
j * digit_size: (j + 1) * digit_size] = digit
start_range = digit_size // 2
end_range = n * digit_size + start_range + 1
pixel_range = np.arange(start_range, end_range, digit_size)
sample_range_x = np.round(grid_x, 1)
sample_range_y = np.round(grid_y, 1)
if not reconstruction:
ax[1].set_xticks(pixel_range)
ax[1].set_yticks(pixel_range)
ax[1].set_xticklabels(sample_range_x)
ax[1].set_yticklabels(sample_range_y)
ax[1].set_xlabel("z[{}]".format(dims[0]))
ax[1].set_ylabel("z[{}]".format(dims[1]))
ax[1].imshow(figure, cmap='Greys_r')
## TODO use same visualization as `ear_img_dimred`