forked from Alfredvc/paac
-
Notifications
You must be signed in to change notification settings - Fork 7
/
logger_utils.py
108 lines (94 loc) · 3.03 KB
/
logger_utils.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
import os
import numpy as np
import time
import json
import tensorflow as tf
import math
import matplotlib.pyplot as plt
def load_args(path):
if path is None:
return {}
with open(path, 'r') as f:
return json.load(f)
def save_args(args, folder, file_name='args.json'):
args = vars(args)
if not os.path.exists(folder):
os.makedirs(folder)
with open(os.path.join(folder, file_name), 'w') as f:
return json.dump(args, f)
def variable_summaries(var, name):
"""Attach a lot of summaries to a Tensor (for TensorBoard visualization)."""
with tf.name_scope(name):
mean = tf.reduce_mean(var)
tf.summary.scalar('mean', mean)
with tf.name_scope('stddev'):
stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
tf.summary.scalar('stddev', stddev)
tf.summary.scalar('max', tf.reduce_max(var))
tf.summary.scalar('min', tf.reduce_min(var))
def get_grid_dim(x):
"""
Transforms x into product of two integers
:param x: int
:return: two ints
"""
factors = prime_powers(x)
if len(factors) % 2 == 0:
i = int(len(factors) / 2)
return factors[i], factors[i - 1]
i = len(factors) // 2
return factors[i], factors[i]
def prime_powers(n):
"""
Compute the factors of a positive integer
Algorithm from https://rosettacode.org/wiki/Factors_of_an_integer#Python
:param n: int
:return: set
"""
factors = set()
for x in range(1, int(math.sqrt(n)) + 1):
if n % x == 0:
factors.add(int(x))
factors.add(int(n // x))
return sorted(factors)
def fig2data ( fig ):
"""
@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
@param fig a matplotlib figure
@return a numpy 2D array of RGB values
"""
# draw the renderer
fig.canvas.draw ( )
# Get the RGB buffer from the figure
w,h = fig.canvas.get_width_height()
rgb = np.fromstring ( fig.canvas.tostring_rgb(), dtype=np.uint8 )
return rgb.reshape(h, w, 3)
def plot_conv_output(conv_img):
"""
Makes plots of results of performing convolution
:param conv_img: numpy array of rank 4
:param name: string, name of convolutional layer
:return: nothing, plots are saved on the disk
"""
w_min = np.min(conv_img)
w_max = np.max(conv_img)
# get number of convolutional filters
num_filters = conv_img.shape[3]
# get number of grid rows and columns
grid_r, grid_c = get_grid_dim(num_filters)
# create figure and axes
fig, axes = plt.subplots(min([grid_r, grid_c]), max([grid_r, grid_c]))
# iterate filters
for l, ax in enumerate(axes.flat):
# get a single image
img = conv_img[0, :, :, l]
# put it on the grid
ax.imshow(img, vmin=w_min, vmax=w_max, interpolation='bicubic', cmap='Greys')
# remove any labels from the axes
ax.set_xticks([])
ax.set_yticks([])
# save figure
fig1 = plt.gcf()
data = fig2data(fig1)
plt.close()
return data