-
Notifications
You must be signed in to change notification settings - Fork 8
/
utils.py
175 lines (140 loc) · 5.34 KB
/
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
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
import os
import logging
import numpy as np
import theano
from pandas import DataFrame, read_hdf
from blocks.extensions import Printing, SimpleExtension
from blocks.main_loop import MainLoop
from blocks.roles import add_role
import sys
debug = sys.gettrace() is not None
logger = logging.getLogger('main.utils')
def shared_param(init, name, cast_float32, role, **kwargs):
if cast_float32:
v = np.float32(init)
p = theano.shared(v, name=name, **kwargs)
if debug:
p.tag.test_value = v
add_role(p, role)
return p
class AttributeDict(dict):
__getattr__ = dict.__getitem__
def __setattr__(self, a, b):
self.__setitem__(a, b)
class DummyLoop(MainLoop):
def __init__(self, extensions):
return super(DummyLoop, self).__init__(algorithm=None,
data_stream=None,
extensions=extensions)
def run(self):
for extension in self.extensions:
extension.main_loop = self
self._run_extensions('before_training')
self._run_extensions('after_training')
class ShortPrinting(Printing):
def __init__(self, to_print, use_log=True, **kwargs):
self.to_print = to_print
self.use_log = use_log
super(ShortPrinting, self).__init__(**kwargs)
def do(self, which_callback, *args):
log = self.main_loop.log
# Iteration
msg = "e {}, i {}:".format(
log.status['epochs_done'],
log.status['iterations_done'])
# Requested channels
items = []
for k, vars in self.to_print.iteritems():
for shortname, vars in vars.iteritems():
if vars is None:
continue
if type(vars) is not list:
vars = [vars]
s = ""
for var in vars:
try:
name = k + '_' + var.name
val = log.current_row[name]
except:
continue
try:
s += ' ' + ' '.join(["%.3g" % v for v in val])
except:
s += " %.3g" % val
if s != "":
items += [shortname + s]
msg = msg + ", ".join(items)
if self.use_log:
logger.info(msg)
else:
print msg
class SaveParams(SimpleExtension):
"""Finishes the training process when triggered."""
def __init__(self, trigger_var, params, save_path, save_every=10, **kwargs):
super(SaveParams, self).__init__(**kwargs)
if trigger_var is None:
self.var_name = None
else:
self.var_name = trigger_var[0] + '_' + trigger_var[1].name
self.save_path = save_path
self.params = params
self.to_save = {}
self.best_value = None
self.add_condition(['after_training'], self.save)
self.add_condition(['on_interrupt'], self.save)
self.save_every = save_every
self.save_every_count = 0
def save(self, which_callback, *args):
if self.var_name is None:
self.to_save = {v.name: v.get_value() for v in self.params}
path = self.save_path + '/trained_params'
logger.info('Saving to %s' % path)
np.savez_compressed(path, **self.to_save)
def do(self, which_callback, *args):
self.save_every_count += 1
if self.save_every and self.save_every_count % self.save_every == 0:
self.save(which_callback, *args)
if self.var_name is None:
return
val = self.main_loop.log.current_row[self.var_name]
if self.best_value is None or val <= self.best_value:
self.best_value = val
logger.info('Best value %f' % val)
self.to_save = {v.name: v.get_value().copy() for v in self.params}
class SaveExpParams(SimpleExtension):
def __init__(self, experiment_params, dir, **kwargs):
super(SaveExpParams, self).__init__(**kwargs)
self.dir = dir
self.experiment_params = experiment_params
def do(self, which_callback, *args):
df = DataFrame.from_dict(self.experiment_params, orient='index')
df.to_hdf(os.path.join(self.dir, 'params'), 'params', mode='w',
complevel=5, complib='blosc')
class SaveLog(SimpleExtension):
def __init__(self, dir, show=None, **kwargs):
super(SaveLog, self).__init__(**kwargs)
self.dir = dir
self.show = show if show is not None else []
def do(self, which_callback, *args):
df = DataFrame.from_dict(self.main_loop.log, orient='index')
df.to_hdf(os.path.join(self.dir, 'log'), 'log', mode='w',
complevel=5, complib='blosc')
def prepare_dir(save_to, results_dir='results'):
base = os.path.join(results_dir, save_to)
i = 0
while True:
name = base + str(i)
try:
os.makedirs(name)
break
except:
i += 1
return name
def load_df(dirpath, filename, varname=None):
varname = filename if varname is None else varname
fn = os.path.join(dirpath, filename)
return read_hdf(fn, varname)
def filter_funcs_prefix(d, pfx):
pfx = 'cmd_'
fp = lambda x: x.find(pfx)
return {n[fp(n) + len(pfx):]: v for n, v in d.iteritems() if fp(n) >= 0}