-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtensorboard_utillities.py
More file actions
277 lines (217 loc) · 11.5 KB
/
tensorboard_utillities.py
File metadata and controls
277 lines (217 loc) · 11.5 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
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
import io
import os
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
from numpy.polynomial.polynomial import Polynomial
from numpy.polynomial.polynomial import polyval
from correlation_analysis import PCC_Matrix
def create_writer(root_dir):
folders = list()
for file in os.listdir(root_dir):
file_path = os.path.join(root_dir, file)
if os.path.isdir(file_path):
folders.append(file_path)
curr_number = 0
while True:
num_str = str(curr_number)
if len(num_str) == 1:
num_str = "0" + num_str
folder = os.path.join(root_dir, num_str)
if not os.path.exists(folder):
break
else:
curr_number = curr_number + 1
os.makedirs(folder)
return tf.summary.create_file_writer(folder), folder
def create_grid_writer(root_dir, params=None):
if params is None:
print('PARAMS is empty, please add arguments.\n')
raise AssertionError
run_dir = f'{root_dir}'
folder = os.path.join(run_dir, ' '.join([str(param) for param in params]))
try:
os.makedirs(folder)
except:
print('LOGPATH exists, appending existing file.\n')
return append_grid_writer(root_dir, params)
return tf.summary.create_file_writer(folder)
def append_grid_writer(root_dir, params=None):
if params is None:
print('PARAMS is empty, please add arguments.\n')
raise AssertionError
run_dir = f'{root_dir}'
folder = os.path.join(run_dir, ' '.join([str(param) for param in params]))
return tf.summary.create_file_writer(folder)
def plot_to_image(figure):
"""Converts the matplotlib plot specified by 'figure' to a PNG image and
returns it. The supplied figure is closed and inaccessible after this call."""
# Save the plot to a PNG in memory.
buf = io.BytesIO()
plt.savefig(buf, format='png', dpi=150)
# Closing the figure prevents it from being displayed directly inside
# the notebook.
plt.close(figure)
buf.seek(0)
# Convert PNG buffer to TF image
image = tf.image.decode_png(buf.getvalue(), channels=4)
# Add the batch dimension
image = tf.expand_dims(image, 0)
return image
def write_poly(writer, epoch, x, f_x, view):
stds = tf.math.reduce_std(f_x, 0)[None]
means = tf.math.reduce_mean(f_x, 0)[None]
norm_f_x = tf.transpose(
tf.math.subtract(f_x, tf.tile(means, tf.constant([1000, 1]))) / tf.tile(stds, tf.constant([1000, 1]))
)
with writer.as_default():
inv_fig, inv_axes = plt.subplots(int(tf.shape(x)[0]), 1, figsize=(8, 12))
for i in range(tf.shape(x)[0]):
inv_axes[i].scatter(x[i].numpy(), norm_f_x[i].numpy(), s=2, label=f'Original')
for deg in [1, 3, 7]:
coeff, diagnostic = Polynomial.fit(x[i].numpy(), norm_f_x[i].numpy(), deg, full=True)
residual = str(np.around(diagnostic[0][0], 4))
inv_axes[i].scatter(x[i].numpy(), polyval(x[i].numpy(), coeff.convert().coef), s=3,
label=f'Degree {deg} Residual {residual}')
inv_axes[i].legend(loc='lower left', bbox_to_anchor=(0, 1.02, 1, 0.2), mode='expand', ncol=3)
plt.tight_layout()
tf.summary.image(f"Poly/{view}", plot_to_image(inv_fig), step=epoch)
writer.flush()
def write_image_summary(writer, epoch, Az_1, Az_2, y_1, y_2, fy_1, fy_2, yhat_1, yhat_2):
with writer.as_default():
# Inverse learning plot
inv_fig, inv_axes = plt.subplots(5, 2, figsize=(10, 15))
for c in range(5):
inv_axes[c, 0].title.set_text(f'View {1} Channel {c+1}')
inv_axes[c, 0].scatter(Az_1[c], tf.transpose(fy_1)[c], label=r'$\mathrm{f}\circledast\mathrm{g}$')
inv_axes[c, 1].title.set_text(f'View {2} Channel {c+1}')
inv_axes[c, 1].scatter(Az_2[c], tf.transpose(fy_2)[c], label=r'$\mathrm{f}\circledast\mathrm{g}$')
plt.tight_layout()
tf.summary.image("Inverse learning", plot_to_image(inv_fig), step=epoch)
writer.flush()
# Reconstruction plot
rec_fig, rec_axes = plt.subplots(5, 2, figsize=(10, 15))
for c in range(5):
rec_axes[c, 0].title.set_text(f'View {1} Channel {c+1}')
rec_axes[c, 0].scatter(y_1[c], tf.transpose(yhat_1)[c])
rec_axes[c, 1].title.set_text(f'View {2} Channel {c+1}')
rec_axes[c, 1].scatter(y_2[c], tf.transpose(yhat_2)[c])
plt.tight_layout()
tf.summary.image("Reconstruction", plot_to_image(rec_fig), step=epoch)
writer.flush()
def write_PCC_summary(writer, epoch, z_1, z_2, epsilon, omega, samples):
with writer.as_default():
fig, axes = plt.subplots(1, 2)
z_s = (z_1, z_2)
sources = (epsilon, omega)
for idx in range(2):
Cov_SE, dim1, dim2 = PCC_Matrix(tf.constant(z_s[idx], tf.float32), sources[idx], samples)
legend_1 = axes[idx].imshow(Cov_SE, cmap='Oranges')
clrbr = fig.colorbar(legend_1, orientation="horizontal", pad=0.15, ax=axes[idx])
for t in clrbr.ax.get_xticklabels():
t.set_fontsize(10)
legend_1.set_clim(0, 1)
clrbr.set_label(r'Correlation', fontsize=15)
axes[idx].set_xticks(np.arange(0, dim2, 1), labels=np.arange(1, dim2+1, 1))
axes[idx].set_yticks(np.arange(0, dim1, 1), labels=np.arange(1, dim2+1, 1))
axes[idx].tick_params(
axis='x',
which='both',
bottom=False,
top=False)
if idx == 0:
axes[idx].set_xlabel(r'$\hat{\mathbf{\varepsilon}}$', fontsize=18)
axes[idx].set_ylabel(r'$\mathbf{z}_{\mathrm{1}}$', fontsize=18)
else:
axes[idx].set_xlabel(r'$\hat{\mathbf{\omega}}$', fontsize=18)
axes[idx].set_ylabel(r'$\mathbf{z}_{\mathrm{2}}$', fontsize=18)
for i in range(len(Cov_SE[0])):
for j in range(len(Cov_SE)):
c = np.around(Cov_SE[j, i], 2)
txt = axes[idx].text(i, j, str(c), va='center', ha='center', color='black', size='x-large')
#txt.set_path_effects([PathEffects.withStroke(linewidth=2, foreground='w')])
plt.tight_layout()
tf.summary.image("PCC Plot", plot_to_image(fig), step=epoch)
writer.flush()
def write_scalar_summary(writer, epoch, list_of_tuples):
with writer.as_default():
for tup in list_of_tuples:
tf.summary.scalar(tup[1], tup[0], step=epoch)
writer.flush()
def write_gradients_summary_mean(writer, epoch, gradients, trainable_variables):
'''
:param writer: used for tensorboard
:param epoch: current epoch of training
:param gradients: containing all gradients of the model
:param trainable_variables: containing all information regarding the corresponding gradient
Filtering the gradients to divide them into different groups
Groups are:
- Weights/Kernels only for each Encoder and Decoder
- Bias only for each Encoder and Decoder
- Encoder gradients (Combining weights/kernels and bias) for each view
- Decoder gradients (Combining weights/kernels and bias) for each view
Note: This functions uses MEAN of the gradients as final output
'''
view_0_encoder_kernel, view_1_encoder_kernel = list(), list()
view_0_encoder_bias, view_1_encoder_bias = list(), list()
view_0_decoder_kernel, view_1_decoder_kernel = list(), list()
view_0_decoder_bias, view_1_decoder_bias = list(), list()
for gradient in gradients:
for gradient_idx, gradient_unit in enumerate(gradient):
if 'View_0_Encoder' in trainable_variables[gradient_idx].name:
if 'kernel' in trainable_variables[gradient_idx].name:
view_0_encoder_kernel.append(gradient_unit)
else:
view_0_encoder_bias.append(gradient_unit)
elif 'View_1_Encoder' in trainable_variables[gradient_idx].name:
if 'kernel' in trainable_variables[gradient_idx].name:
view_1_encoder_kernel.append(gradient_unit)
else:
view_1_encoder_bias.append(gradient_unit)
elif 'View_0_Decoder' in trainable_variables[gradient_idx].name:
if 'kernel' in trainable_variables[gradient_idx].name:
view_0_decoder_kernel.append(gradient_unit)
else:
view_0_decoder_bias.append(gradient_unit)
elif 'View_1_Decoder' in trainable_variables[gradient_idx].name:
if 'kernel' in trainable_variables[gradient_idx].name:
view_1_decoder_kernel.append(gradient_unit)
else:
view_1_decoder_bias.append(gradient_unit)
grad_encoder_0_kernel = np.mean([np.linalg.norm(grad) for grad in view_0_encoder_kernel])
grad_encoder_1_kernel = np.mean([np.linalg.norm(grad) for grad in view_1_encoder_kernel])
grad_encoder_0_bias = np.mean([np.linalg.norm(grad) for grad in view_0_encoder_bias])
grad_encoder_1_bias = np.mean([np.linalg.norm(grad) for grad in view_1_encoder_bias])
grad_decoder_0_kernel = np.mean([np.linalg.norm(grad) for grad in view_0_decoder_kernel])
grad_decoder_1_kernel = np.mean([np.linalg.norm(grad) for grad in view_1_decoder_kernel])
grad_decoder_0_bias = np.mean([np.linalg.norm(grad) for grad in view_0_decoder_bias])
grad_decoder_1_bias = np.mean([np.linalg.norm(grad) for grad in view_1_decoder_bias])
units = [('Gradient Units MEAN/Encoder View 0 Kernel', grad_encoder_0_kernel),
('Gradient Units MEAN/Encoder View 0 Bias', grad_encoder_0_bias),
('Gradient Units MEAN/Encoder View 1 Kernel', grad_encoder_1_kernel),
('Gradient Units MEAN/Encoder View 1 Bias', grad_encoder_1_bias),
('Gradient Units MEAN/Decoder View 0 Kernel', grad_decoder_0_kernel),
('Gradient Units MEAN/Decoder View 0 Bias', grad_decoder_0_bias),
('Gradient Units MEAN/Decoder View 1 Kernel', grad_decoder_1_kernel),
('Gradient Units MEAN/Decoder View 1 Bias', grad_decoder_1_bias)
]
# Concatenating two lists of norms and taking the sum
grad_encoder_0 = np.mean([np.linalg.norm(grad) for grad in view_0_encoder_kernel] +
[np.linalg.norm(grad) for grad in view_0_encoder_bias])
grad_encoder_1 = np.mean([np.linalg.norm(grad) for grad in view_1_encoder_kernel] +
[np.linalg.norm(grad) for grad in view_1_encoder_bias])
encoders = [('Gradient Encoders MEAN/View 0', grad_encoder_0),
('Gradient Encoders MEAN/View 1', grad_encoder_1)]
grad_decoder_0 = np.mean([np.linalg.norm(grad) for grad in view_0_decoder_kernel] +
[np.linalg.norm(grad) for grad in view_0_decoder_bias])
grad_decoder_1 = np.mean([np.linalg.norm(grad) for grad in view_1_decoder_kernel] +
[np.linalg.norm(grad) for grad in view_1_decoder_bias])
decoders = [('Gradient Decoders MEAN/View 0', grad_decoder_0),
('Gradient Decoders MEAN/View 1', grad_decoder_1)]
with writer.as_default():
for path, variable in units:
tf.summary.scalar(path, variable, step=epoch)
for path, variable in encoders:
tf.summary.scalar(path, variable, step=epoch)
for path, variable in decoders:
tf.summary.scalar(path, variable, step=epoch)