code
stringlengths
17
6.64M
def flatten_shape_dim(shape): return reduce(operator.mul, shape, 1)
def print_lasagne_layer(layer, prefix=''): params = '' if layer.name: params += (', name=' + layer.name) if getattr(layer, 'nonlinearity', None): params += (', nonlinearity=' + layer.nonlinearity.__name__) params = params[2:] print(((((prefix + layer.__class__.__name__) + '[') + pa...
def unflatten_tensor_variables(flatarr, shapes, symb_arrs): import theano.tensor as TT import numpy as np arrs = [] n = 0 for (shape, symb_arr) in zip(shapes, symb_arrs): size = np.prod(list(shape)) arr = flatarr[n:(n + size)].reshape(shape) if (arr.type.broadcastable != sy...
def sliced_fun(f, n_slices): def sliced_f(sliced_inputs, non_sliced_inputs=None): if (non_sliced_inputs is None): non_sliced_inputs = [] if isinstance(non_sliced_inputs, tuple): non_sliced_inputs = list(non_sliced_inputs) n_paths = len(sliced_inputs[0]) sli...
def stdize(data, eps=1e-06): return ((data - np.mean(data, axis=0)) / (np.std(data, axis=0) + eps))
def iterate_minibatches_generic(input_lst=None, batchsize=None, shuffle=False): if (batchsize is None): batchsize = len(input_lst[0]) assert all(((len(x) == len(input_lst[0])) for x in input_lst)) if shuffle: indices = np.arange(len(input_lst[0])) np.random.shuffle(indices) for...
class StubBase(object): def __getitem__(self, item): return StubMethodCall(self, '__getitem__', args=[item], kwargs=dict()) def __getattr__(self, item): try: return super(self.__class__, self).__getattribute__(item) except AttributeError: if (item.startswith('...
class BinaryOp(Serializable): def __init__(self): Serializable.quick_init(self, locals()) def rdiv(self, a, b): return (b / a)
class StubAttr(StubBase): def __init__(self, obj, attr_name): self.__dict__['_obj'] = obj self.__dict__['_attr_name'] = attr_name @property def obj(self): return self.__dict__['_obj'] @property def attr_name(self): return self.__dict__['_attr_name'] def __st...
class StubMethodCall(StubBase, Serializable): def __init__(self, obj, method_name, args, kwargs): self._serializable_initialized = False Serializable.quick_init(self, locals()) self.obj = obj self.method_name = method_name self.args = args self.kwargs = kwargs ...
class StubClass(StubBase): def __init__(self, proxy_class): self.proxy_class = proxy_class def __call__(self, *args, **kwargs): if (len(args) > 0): spec = inspect.getargspec(self.proxy_class.__init__) kwargs = dict(list(zip(spec.args[1:], args)), **kwargs) ...
class StubObject(StubBase): def __init__(self, __proxy_class, *args, **kwargs): if (len(args) > 0): spec = inspect.getargspec(__proxy_class.__init__) kwargs = dict(list(zip(spec.args[1:], args)), **kwargs) args = tuple() self.proxy_class = __proxy_class ...
class VariantDict(AttrDict): def __init__(self, d, hidden_keys): super(VariantDict, self).__init__(d) self._hidden_keys = hidden_keys def dump(self): return {k: v for (k, v) in self.items() if (k not in self._hidden_keys)}
class VariantGenerator(object): '\n Usage:\n\n vg = VariantGenerator()\n vg.add("param1", [1, 2, 3])\n vg.add("param2", [\'x\', \'y\'])\n vg.variants() => # all combinations of [1,2,3] x [\'x\',\'y\']\n\n Supports noncyclic dependency among parameters:\n vg = VariantGenerator()\n vg.add("p...
def variant(*args, **kwargs): def _variant(fn): fn.__is_variant = True fn.__variant_config = kwargs return fn if ((len(args) == 1) and isinstance(args[0], collections.Callable)): return _variant(args[0]) return _variant
def stub(glbs): for (k, v) in list(glbs.items()): if (isinstance(v, type) and (v != StubClass)): glbs[k] = StubClass(v)
def query_yes_no(question, default='yes'): 'Ask a yes/no question via raw_input() and return their answer.\n\n "question" is a string that is presented to the user.\n "default" is the presumed answer if the user just hits <Enter>.\n It must be "yes" (the default), "no" or None (meaning\n an an...
def run_experiment_lite(stub_method_call=None, batch_tasks=None, exp_prefix='experiment', exp_name=None, log_dir=None, script='scripts/run_experiment_lite.py', python_command='python', mode='local', dry=False, docker_image=None, aws_config=None, env=None, variant=None, use_gpu=False, sync_s3_pkl=False, sync_log_on_te...
def ensure_dir(dirname): '\n Ensure that a named directory exists; if it does not, attempt to create it.\n ' try: os.makedirs(dirname) except OSError as e: if (e.errno != errno.EEXIST): raise
def _shellquote(s): 'Return a shell-escaped version of the string *s*.' if (not s): return "''" if (_find_unsafe(s) is None): return s return (("'" + s.replace("'", '\'"\'"\'')) + "'")
def _to_param_val(v): if (v is None): return '' elif isinstance(v, list): return ' '.join(map(_shellquote, list(map(str, v)))) else: return _shellquote(str(v))
def to_local_command(params, python_command='python', script=osp.join(config.PROJECT_PATH, 'scripts/run_experiment.py'), use_gpu=False): command = ((python_command + ' ') + script) if (use_gpu and (not config.USE_TF)): command = ("THEANO_FLAGS='device=gpu,dnn.enabled=auto' " + command) for (k, v) ...
def to_docker_command(params, docker_image, python_command='python', script='scripts/run_experiment.py', pre_commands=None, use_tty=False, post_commands=None, dry=False, use_gpu=False, env=None, local_code_dir=None): '\n :param params: The parameters for the experiment. If logging directory parameters are prov...
def dedent(s): lines = [l.strip() for l in s.split('\n')] return '\n'.join(lines)
def launch_ec2(params_list, exp_prefix, docker_image, code_full_path, python_command='python', pre_commands=None, script='scripts/run_experiment.py', aws_config=None, dry=False, terminate_machine=True, use_gpu=False, sync_s3_pkl=False, sync_log_on_termination=True, periodic_sync=True, periodic_sync_interval=15): ...
def s3_sync_code(config, dry=False): global S3_CODE_PATH if (S3_CODE_PATH is not None): return S3_CODE_PATH base = config.AWS_CODE_SYNC_S3_PATH has_git = True if config.FAST_CODE_SYNC: try: current_commit = subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip().d...
def upload_file_to_s3(script_content): import tempfile import uuid f = tempfile.NamedTemporaryFile(delete=False) f.write(script_content) f.close() remote_path = os.path.join(config.AWS_CODE_SYNC_S3_PATH, 'oversize_bash_scripts', str(uuid.uuid4())) subprocess.check_call(['aws', 's3', 'cp', ...
def to_lab_kube_pod(params, docker_image, code_full_path, python_command='python', script='scripts/run_experiment.py', is_gpu=False, sync_s3_pkl=False, periodic_sync=True, periodic_sync_interval=15, sync_all_data_node_to_s3=False, terminate_machine=True): '\n :param params: The parameters for the experiment. I...
def concretize(maybe_stub): if isinstance(maybe_stub, StubMethodCall): obj = concretize(maybe_stub.obj) method = getattr(obj, maybe_stub.method_name) args = concretize(maybe_stub.args) kwargs = concretize(maybe_stub.kwargs) return method(*args, **kwargs) elif isinstance...
def _add_output(file_name, arr, fds, mode='a'): if (file_name not in arr): mkdir_p(os.path.dirname(file_name)) arr.append(file_name) fds[file_name] = open(file_name, mode)
def _remove_output(file_name, arr, fds): if (file_name in arr): fds[file_name].close() del fds[file_name] arr.remove(file_name)
def push_prefix(prefix): _prefixes.append(prefix) global _prefix_str _prefix_str = ''.join(_prefixes)
def add_text_output(file_name): _add_output(file_name, _text_outputs, _text_fds, mode='a')
def remove_text_output(file_name): _remove_output(file_name, _text_outputs, _text_fds)
def add_tabular_output(file_name): _add_output(file_name, _tabular_outputs, _tabular_fds, mode='w')
def remove_tabular_output(file_name): if (_tabular_fds[file_name] in _tabular_header_written): _tabular_header_written.remove(_tabular_fds[file_name]) _remove_output(file_name, _tabular_outputs, _tabular_fds)
def set_snapshot_dir(dir_name): global _snapshot_dir _snapshot_dir = dir_name
def get_snapshot_dir(): return _snapshot_dir
def get_snapshot_mode(): return _snapshot_mode
def set_snapshot_mode(mode): global _snapshot_mode _snapshot_mode = mode
def get_snapshot_gap(): return _snapshot_gap
def set_snapshot_gap(gap): global _snapshot_gap _snapshot_gap = gap
def set_log_tabular_only(log_tabular_only): global _log_tabular_only _log_tabular_only = log_tabular_only
def get_log_tabular_only(): return _log_tabular_only
def log(s, with_prefix=True, with_timestamp=True, color=None): out = s if with_prefix: out = (_prefix_str + out) if with_timestamp: now = datetime.datetime.now(dateutil.tz.tzlocal()) timestamp = now.strftime('%Y-%m-%d %H:%M:%S.%f %Z') out = ('%s | %s' % (timestamp, out)) ...
def record_tabular(key, val): _tabular.append(((_tabular_prefix_str + str(key)), str(val)))
def push_tabular_prefix(key): _tabular_prefixes.append(key) global _tabular_prefix_str _tabular_prefix_str = ''.join(_tabular_prefixes)
def pop_tabular_prefix(): del _tabular_prefixes[(- 1)] global _tabular_prefix_str _tabular_prefix_str = ''.join(_tabular_prefixes)
@contextmanager def prefix(key): push_prefix(key) try: (yield) finally: pop_prefix()
@contextmanager def tabular_prefix(key): push_tabular_prefix(key) (yield) pop_tabular_prefix()
class TerminalTablePrinter(object): def __init__(self): self.headers = None self.tabulars = [] def print_tabular(self, new_tabular): if (self.headers is None): self.headers = [x[0] for x in new_tabular] else: assert (len(self.headers) == len(new_tabula...
def dump_tabular(*args, **kwargs): wh = kwargs.pop('write_header', None) if (len(_tabular) > 0): if _log_tabular_only: table_printer.print_tabular(_tabular) else: for line in tabulate(_tabular).split('\n'): log(line, *args, **kwargs) tabular_dict...
def pop_prefix(): del _prefixes[(- 1)] global _prefix_str _prefix_str = ''.join(_prefixes)
def save_itr_params(itr, params): if _snapshot_dir: if (_snapshot_mode == 'all'): file_name = osp.join(_snapshot_dir, ('itr_%d.pkl' % itr)) joblib.dump(params, file_name, compress=3) elif (_snapshot_mode == 'last'): file_name = osp.join(_snapshot_dir, 'params.pk...
def log_parameters(log_file, args, classes): log_params = {} for (param_name, param_value) in args.__dict__.items(): if any([param_name.startswith(x) for x in list(classes.keys())]): continue log_params[param_name] = param_value for (name, cls) in classes.items(): if is...
def stub_to_json(stub_sth): from rllab.misc import instrument if isinstance(stub_sth, instrument.StubObject): assert (len(stub_sth.args) == 0) data = dict() for (k, v) in stub_sth.kwargs.items(): data[k] = stub_to_json(v) data['_name'] = ((stub_sth.proxy_class.__mod...
class MyEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, type): return {'$class': ((o.__module__ + '.') + o.__name__)} elif isinstance(o, Enum): return {'$enum': ((((o.__module__ + '.') + o.__class__.__name__) + '.') + o.name)} return json.JSONEnco...
def log_parameters_lite(log_file, args): log_params = {} for (param_name, param_value) in args.__dict__.items(): log_params[param_name] = param_value if (args.args_data is not None): stub_method = pickle.loads(base64.b64decode(args.args_data)) method_args = stub_method.kwargs ...
def log_variant(log_file, variant_data): mkdir_p(os.path.dirname(log_file)) if hasattr(variant_data, 'dump'): variant_data = variant_data.dump() variant_json = stub_to_json(variant_data) with open(log_file, 'w') as f: json.dump(variant_json, f, indent=2, sort_keys=True, cls=MyEncoder)
def record_tabular_misc_stat(key, values): record_tabular((key + 'Average'), np.average(values)) record_tabular((key + 'Std'), np.std(values)) record_tabular((key + 'Median'), np.median(values)) record_tabular((key + 'Min'), np.amin(values)) record_tabular((key + 'Max'), np.amax(values))
def compute_rect_vertices(fromp, to, radius): (x1, y1) = fromp (x2, y2) = to if (abs((y1 - y2)) < 1e-06): dx = 0 dy = radius else: dx = ((radius * 1.0) / (((((x1 - x2) / (y1 - y2)) ** 2) + 1) ** 0.5)) dy = (((radius ** 2) - (dx ** 2)) ** 0.5) dy *= ((- 1) if (((...
def plot_experiments(name_or_patterns, legend=False, post_processing=None, key='AverageReturn'): if (not isinstance(name_or_patterns, (list, tuple))): name_or_patterns = [name_or_patterns] data_folder = osp.abspath(osp.join(osp.dirname(__file__), '../../data')) files = [] for name_or_pattern i...
class Experiment(object): def __init__(self, progress, params, pkl_data=None): self.progress = progress self.params = params self.pkl_data = pkl_data self.flat_params = self._flatten_params(params) self.name = params['exp_name'] def _flatten_params(self, params, depth...
def uniq(seq): seen = set() seen_add = seen.add return [x for x in seq if (not ((x in seen) or seen_add(x)))]
class ExperimentDatabase(object): def __init__(self, data_folder, names_or_patterns='*'): self._load_experiments(data_folder, names_or_patterns) def _read_data(self, progress_file): entries = dict() with open(progress_file, 'rb') as csvfile: reader = csv.DictReader(csvfil...
def overrides(method): "Decorator to indicate that the decorated method overrides a method in superclass.\n The decorator code is executed while loading class. Using this method should have minimal runtime performance\n implications.\n\n This is based on my idea about how to do this and fwc:s highly impr...
def _get_base_classes(frame, namespace): return [_get_base_class(class_name_components, namespace) for class_name_components in _get_base_class_names(frame)]
def _get_base_class_names(frame): 'Get baseclass names from the code object' (co, lasti) = (frame.f_code, frame.f_lasti) code = co.co_code i = 0 extended_arg = 0 extends = [] while (i <= lasti): c = code[i] op = ord(c) i += 1 if (op >= dis.HAVE_ARGUMENT): ...
def _get_base_class(components, namespace): obj = namespace[components[0]] for component in components[1:]: obj = getattr(obj, component) return obj
def classesinmodule(module): md = module.__dict__ return [md[c] for c in md if (isinstance(md[c], type) and (md[c].__module__ == module.__name__))]
def locate_with_hint(class_path, prefix_hints=[]): module_or_class = locate(class_path) if (module_or_class is None): hint = '.'.join(prefix_hints) module_or_class = locate(((hint + '.') + class_path)) return module_or_class
def load_class(class_path, superclass=None, prefix_hints=[]): module_or_class = locate_with_hint(class_path, prefix_hints) if (module_or_class is None): raise ValueError(('Cannot find module or class under path %s' % class_path)) if (type(module_or_class) == types.ModuleType): if superclas...
def weighted_sample(weights, objects): '\n Return a random item from objects, with the weighting defined by weights\n (which must sum to 1).\n ' cs = np.cumsum(weights) idx = sum((cs < np.random.rand())) return objects[min(idx, (len(objects) - 1))]
def weighted_sample_n(prob_matrix, items): s = prob_matrix.cumsum(axis=1) r = np.random.rand(prob_matrix.shape[0]) k = (s < r.reshape(((- 1), 1))).sum(axis=1) n_items = len(items) return items[np.minimum(k, (n_items - 1))]
def softmax(x): shifted = (x - np.max(x, axis=(- 1), keepdims=True)) expx = np.exp(shifted) return (expx / np.sum(expx, axis=(- 1), keepdims=True))
def softmax_sym(x): return theano.tensor.nnet.softmax(x)
def cat_entropy(x): return (- np.sum((x * np.log(x)), axis=(- 1)))
def cat_perplexity(x): return np.exp(cat_entropy(x))
def explained_variance_1d(ypred, y): assert ((y.ndim == 1) and (ypred.ndim == 1)) vary = np.var(y) if np.isclose(vary, 0): if (np.var(ypred) > 0): return 0 else: return 1 return (1 - (np.var((y - ypred)) / (vary + 1e-08)))
def to_onehot(ind, dim): ret = np.zeros(dim) ret[ind] = 1 return ret
def to_onehot_n(inds, dim): ret = np.zeros((len(inds), dim)) ret[(np.arange(len(inds)), inds)] = 1 return ret
def to_onehot_sym(ind, dim): assert (ind.ndim == 1) return theano.tensor.extra_ops.to_one_hot(ind, dim)
def from_onehot(v): return np.nonzero(v)[0][0]
def from_onehot_n(v): if (len(v) == 0): return [] return np.nonzero(v)[1]
def normalize_updates(old_mean, old_std, new_mean, new_std, old_W, old_b): '\n Compute the updates for normalizing the last (linear) layer of a neural\n network\n ' new_W = ((old_W * old_std[0]) / (new_std[0] + 1e-06)) new_b = ((((old_b * old_std[0]) + old_mean[0]) - new_mean[0]) / (new_std[0] + ...
def discount_cumsum(x, discount): return scipy.signal.lfilter([1], [1, float((- discount))], x[::(- 1)], axis=0)[::(- 1)]
def discount_return(x, discount): return np.sum((x * (discount ** np.arange(len(x)))))
def rk4(derivs, y0, t, *args, **kwargs): '\n Integrate 1D or ND system of ODEs using 4-th order Runge-Kutta.\n This is a toy implementation which may be useful if you find\n yourself stranded on a system w/o scipy. Otherwise use\n :func:`scipy.integrate`.\n\n *y0*\n initial state vector\n\n...
def _pipe_segment_with_colons(align, colwidth): "Return a segment of a horizontal line with optional colons which\n indicate column's alignment (as in `pipe` output format)." w = colwidth if (align in ['right', 'decimal']): return (('-' * (w - 1)) + ':') elif (align == 'center'): re...
def _pipe_line_with_colons(colwidths, colaligns): "Return a horizontal line with optional colons to indicate column's\n alignment (as in `pipe` output format)." segments = [_pipe_segment_with_colons(a, w) for (a, w) in zip(colaligns, colwidths)] return (('|' + '|'.join(segments)) + '|')
def _mediawiki_row_with_attrs(separator, cell_values, colwidths, colaligns): alignment = {'left': '', 'right': 'align="right"| ', 'center': 'align="center"| ', 'decimal': 'align="right"| '} values_with_attrs = [(((' ' + alignment.get(a, '')) + c) + ' ') for (c, a) in zip(cell_values, colaligns)] colsep = ...
def _latex_line_begin_tabular(colwidths, colaligns): alignment = {'left': 'l', 'right': 'r', 'center': 'c', 'decimal': 'r'} tabular_columns_fmt = ''.join([alignment.get(a, 'l') for a in colaligns]) return (('\\begin{tabular}{' + tabular_columns_fmt) + '}\n\\hline')
def simple_separated_format(separator): 'Construct a simple TableFormat with columns separated by a separator.\n\n >>> tsv = simple_separated_format("\\t") ; tabulate([["foo", 1], ["spam", 23]], tablefmt=tsv) == \'foo \\t 1\\nspam\\t23\'\n True\n\n ' return TableFormat(None, None, None, None,...
def _isconvertible(conv, string): try: n = conv(string) return True except ValueError: return False
def _isnumber(string): '\n >>> _isnumber("123.45")\n True\n >>> _isnumber("123")\n True\n >>> _isnumber("spam")\n False\n ' return _isconvertible(float, string)
def _isint(string): '\n >>> _isint("123")\n True\n >>> _isint("123.45")\n False\n ' return ((type(string) is int) or ((isinstance(string, _binary_type) or isinstance(string, _text_type)) and _isconvertible(int, string)))
def _type(string, has_invisible=True): 'The least generic type (type(None), int, float, str, unicode).\n\n >>> _type(None) is type(None)\n True\n >>> _type("foo") is type("")\n True\n >>> _type("1") is type(1)\n True\n >>> _type(\'\x1b[31m42\x1b[0m\') is type(42)\n True\n >>> _type(\'\x...
def _afterpoint(string): 'Symbols after a decimal point, -1 if the string lacks the decimal point.\n\n >>> _afterpoint("123.45")\n 2\n >>> _afterpoint("1001")\n -1\n >>> _afterpoint("eggs")\n -1\n >>> _afterpoint("123e45")\n 2\n\n ' if _isnumber(string): if _isint(string): ...
def _padleft(width, s, has_invisible=True): "Flush right.\n\n >>> _padleft(6, 'яйца') == ' яйца'\n True\n\n " iwidth = (((width + len(s)) - len(_strip_invisible(s))) if has_invisible else width) fmt = ('{0:>%ds}' % iwidth) return fmt.format(s)
def _padright(width, s, has_invisible=True): "Flush left.\n\n >>> _padright(6, 'яйца') == 'яйца '\n True\n\n " iwidth = (((width + len(s)) - len(_strip_invisible(s))) if has_invisible else width) fmt = ('{0:<%ds}' % iwidth) return fmt.format(s)