-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathploty.py
174 lines (126 loc) · 4.42 KB
/
ploty.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
import matplotlib
matplotlib.use("Agg")
import tensorflow as tf
from matplotlib import pyplot as plt
from IPython.display import clear_output
import csv
try:
from google.colab import auth
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
except:
pass
class Ploty(object):
def __init__(self, output_path, title='', x='', y="Time to training complete", legend=True, log_y=False, log_x=False, clear_screen=True, terminal=True, auto_render=True):
self.output_path = output_path
self.title = title
self.label_x = x
self.label_y = y
self.log_y = log_y
self.log_x = log_x
self.clear_screen = clear_screen
self.legend = legend
self.terminal = terminal
self.auto_render = auto_render
self.header = ["x", "y", "label"]
self.datas = {}
self.c_i = 0
self.cmap = plt.cm.get_cmap('hsv', 10)
self.fig = plt.figure()
self.ax = self.fig.add_subplot(111)
if self.log_x:
self.ax.set_xscale('log')
if self.log_y:
self.ax.set_yscale('log')
def ensure(self, name, extra_data):
if name not in self.datas:
self.datas[name] = {
"c": self.cmap(self.c_i),
"x": [],
"y": [],
"m": ".",
"l": '-'
}
for i in extra_data.keys():
self.datas[name][i] = []
if i not in self.header:
self.header.append(i)
self.c_i += 1
# This method assumes extra_data will have the same keys every single call, otherwise csv writing will crash
def add_result(self, x, y, name, marker="o", line="-", extra_data={}):
self.ensure(name, extra_data)
self.datas[name]["x"].append(x)
self.datas[name]["y"].append(y)
self.datas[name]["m"] = marker
self.datas[name]["l"] = line
for key, value in extra_data.items():
self.datas[name][key].append(value)
if self.terminal:
print(f'{{"metric": "{name}", "value": {y}, "x": {x} }}')
if self.auto_render:
self.render()
self.save_csv()
def runningMeanFast(x, N):
return np.convolve(np.array(x), np.ones((N,))/N)[(N-1):]
def render(self):
self.render_pre()
for k, d in self.datas.items():
plt.plot(d['x'], d['y'], d["l"]+d["m"], label=k)
self.render_post()
def render_pre(self):
if self.clear_screen and not self.terminal:
clear_output()
plt.cla()
def render_post(self):
img_name = self.output_path + '/' + self.title.replace(" ", "_") + '.png'
artists = []
self.fig.suptitle(self.title, fontsize=14, fontweight='bold')
self.ax.set_xlabel(self.label_x)
self.ax.set_ylabel(self.label_y)
if self.legend:
lgd = plt.legend(bbox_to_anchor=(1.04,0.5), loc="center left", borderaxespad=0)
artists.append(lgd)
try:
os.remove(img_name)
except:
pass
plt.savefig(img_name, bbox_extra_artists=artists, bbox_inches='tight')
tf.logging.info("Saved image: " + img_name)
if not self.terminal:
plt.show()
def save_csv(self):
try:
os.remove(csv_name)
except:
pass
csv_name = self.output_path + '/' + self.title.replace(" ", "_") + '.csv'
with open(csv_name, 'w') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(self.header)
for k, d in self.datas.items():
for i in range(len(d["x"])):
row = [
k if h == "label" else d[h][i] for h in self.header
]
writer.writerow(row)
tf.logging.info("Saved CSV: " + csv_name)
def copy_to_drive(self, snapshot=False):
auth.authenticate_user()
drive_service = build('drive', 'v3')
if snapshot:
name = self.title + "_latest"
else:
name = self.title +'_' + str(datetime.now())
def do_copy(source_name, dest_name, mime):
file_metadata = {
'name': dest_name,
'mimeType': mime
}
media = MediaFileUpload(self.output_path + source_name,
mimetype=file_metadata['mimeType'],
resumable=True)
created = drive_service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()
do_copy(self.title+'.csv', name + '.csv', 'text/csv')
do_copy(self.title+'.png', name + '.png', 'image/png')