forked from praveenv253/ann-info-flow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_utils.py
More file actions
executable file
·142 lines (113 loc) · 5.03 KB
/
Copy pathplot_utils.py
File metadata and controls
executable file
·142 lines (113 loc) · 5.03 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
#!/usr/bin/env python3
from __future__ import print_function, division
import numpy as np
import matplotlib.pyplot as plt
import os
import sys
import joblib
from param_utils import init_params
def init_plots(vis):
# Initialize the plotting axes and add them to the namespace
vis.fig = plt.figure(figsize=(15, 5))
vis.fig.canvas.toolbar_visible = False
vis.fig.canvas.header_visible = False
vis.fig.canvas.footer_visible = False
vis.fig.canvas.resizable = False
vis.ax_weights = vis.fig.add_subplot(1, 3, 1, aspect='equal')
vis.ax_weights.set_axis_off()
vis.ax_weights.set_title('ANN Weights')
vis.ax_bias_flows = vis.fig.add_subplot(1, 3, 2, aspect='equal')
vis.ax_bias_flows.set_axis_off()
vis.ax_bias_flows.set_title('Weighted Bias Flows')
vis.ax_acc_flows = vis.fig.add_subplot(1, 3, 3, aspect='equal')
vis.ax_acc_flows.set_axis_off()
vis.ax_acc_flows.set_title('Weighted Accuracy Flows')
plt.tight_layout()
def plot_ann(layer_sizes, weights, plot_params=None, ax=None, flow_type='bias', info_method='', label_name=''):
"""
Plots a visualization of a trained neural network with given weights.
Based on a gist by Colin Raffel
(https://gist.github.com/craffel/2d727968c3aaebd10359)
"""
if ax is None:
plt.figure(figsize=(6, 6))
ax = plt.gca()
plt.axis('off')
if plot_params is None:
plot_params = (0.1, 0.9, 0.9, 0.1)
left, right, top, bottom = plot_params
num_layers = len(layer_sizes)
v_spacing = (top - bottom) / max(layer_sizes)
h_spacing = (right - left) / (num_layers - 1)
# Plot circles for neurons
for n, layer_size in enumerate(layer_sizes):
layer_top = v_spacing * (layer_size - 1) / 2 + (top + bottom) / 2
for m in range(layer_size):
circle = plt.Circle((n*h_spacing + left, layer_top - m*v_spacing),
h_spacing/4, color='w', ec='k', zorder=4)
ax.add_artist(circle)
# Normalize edge weights to lie between -1 and +1
# max_weight = max(np.abs(w).max() for w in weights)
# normalized_weights = [w / max_weight for w in weights]
normalized_weights = [w / 0.5 for w in weights] # MM normalizing to .5, since that's around the max we see across both tasks
# normalized_weights = weights # MM normalizing to 1, since max entropy for this task is 1
alpha0 = 0.1 # MM originally 0.3
t0, tmax = (0.5, 5)
# Plot lines for edges
for n, (layer_size_a, layer_size_b) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])):
layer_top_a = v_spacing*(layer_size_a - 1)/2 + (top + bottom)/2
layer_top_b = v_spacing*(layer_size_b - 1)/2 + (top + bottom)/2
for m in range(layer_size_a):
for o in range(layer_size_b):
weight = normalized_weights[n].reshape((layer_size_b, layer_size_a))[o, m]
if flow_type == 'acc':
color = 'C0'
elif flow_type == 'bias':
color = 'C1'
else:
color = 'C2'
alpha = alpha0 + abs(weight) * (1 - alpha0)
thickness = t0 + abs(weight) * (tmax - t0)
line = plt.Line2D([n*h_spacing + left, (n + 1)*h_spacing + left],
[layer_top_a - m*v_spacing, layer_top_b - o*v_spacing],
color=color, alpha=alpha, linewidth=thickness)
ax.add_artist(line)
if label_name != '':
ax.set_title(label_name, fontsize=18)
elif flow_type == 'bias':
ax.set_title("Bias flow visualization\n(Dataset: Synthetic, MI est: %s)" % info_method ,fontsize=18)
else:
ax.set_title("Accuracy flow visualization\n(Dataset: Synthetic, MI est: %s)" % info_method ,fontsize=18)
return ax
if __name__ == '__main__':
if len(sys.argv) == 1:
print("Please provide the dataset (adult, tinyscm), MI estimation method (corr,linear-svm,kernel-svm), and run number.")
exit()
if len(sys.argv) > 1:
dataset = sys.argv[1]
else:
params = init_params()
dataset = params.dataset
if len(sys.argv) > 2:
subfolder = sys.argv[2]
else:
subfolder = ''
if len(sys.argv) > 3:
run = int(sys.argv[3])
else:
run = 0
#subfolder = 'linear-svm'
results_dir = 'results-%s' % dataset
results_subfolder = os.path.join(results_dir, subfolder)
params=init_params(dataset=dataset)
nets=joblib.load(params.annfile)
layer_sizes = nets[run].layer_sizes
#weights = nets[0].get_weights() # Plot just the network weights.
bias_flows=joblib.load(results_subfolder + '/analyzed-data.pkl')[run][2][:-1]
weights = [abs(w) for w in bias_flows]
plot_ann(layer_sizes, weights, flow_type='bias', info_method=subfolder)
#weights = nets[0].get_weights()
acc_flows=joblib.load(results_subfolder + '/analyzed-data.pkl')[run][5][:-1]
weights = [abs(w) for w in acc_flows]
plot_ann(layer_sizes, weights, flow_type='acc', info_method=subfolder)
plt.show()