Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def save(df, path): if os.environ.get('TENSORPACK_COMPATIBLE_SERIALIZE', 'msgpack') == 'msgpack': def _dumps(dp): return dumps(dp) else: def _dumps(dp): return dumps(dp).to_pybytes() si...
[ "\n Args:\n df (DataFlow): the DataFlow to serialize.\n path (str): output tfrecord file.\n " ]
Please provide a description of the function:def load(path, size=None): gen = tf.python_io.tf_record_iterator(path) ds = DataFromGenerator(gen) ds = MapData(ds, loads) if size is not None: ds = FixedSizeData(ds, size) return ds
[ "\n Args:\n size (int): total number of records. If not provided, the returned dataflow will have no `__len__()`.\n It's needed because this metadata is not stored in the TFRecord file.\n " ]
Please provide a description of the function:def save(df, path, data_paths): size = _reset_df_and_get_size(df) buffer = defaultdict(list) with get_tqdm(total=size) as pbar: for dp in df: assert len(dp) == len(data_paths), "Datapoint has {} components!".forma...
[ "\n Args:\n df (DataFlow): the DataFlow to serialize.\n path (str): output hdf5 file.\n data_paths (list[str]): list of h5 paths. It should have the same\n length as each datapoint, and each path should correspond to one\n component of the datapo...
Please provide a description of the function:def setup_keras_trainer( trainer, get_model, input_signature, target_signature, input, optimizer, loss, metrics): assert isinstance(optimizer, tf.train.Optimizer), optimizer assert isinstance(loss, list), loss assert len(loss) >= 1, "...
[ "\n Args:\n trainer (SingleCostTrainer):\n get_model (input1, input2, ... -> tf.keras.Model):\n A function which takes tensors, builds and returns a Keras model.\n It will be part of the tower function.\n input (InputSource):\n optimizer (tf.train.Optimizer):\n ...
Please provide a description of the function:def compile(self, optimizer, loss, metrics=None): if isinstance(loss, six.string_types): loss = [loss] if metrics is None: metrics = [] if isinstance(metrics, six.string_types): metrics = [metrics] ...
[ "\n Args:\n optimizer (tf.train.Optimizer):\n loss, metrics: string or list of strings\n " ]
Please provide a description of the function:def fit(self, validation_data=None, **kwargs): callbacks = kwargs.pop('callbacks', []) if validation_data is not None: # There is no way to guess where users want this callback. So we have to choose one. # MinSaver may need re...
[ "\n Args:\n validation_data (DataFlow or InputSource): to be used for inference.\n The inference callback is added as the first in the callback list.\n If you need to use it in a different order, please write it in the callback list manually.\n kwargs: same...
Please provide a description of the function:def get_dorefa(bitW, bitA, bitG): def quantize(x, k): n = float(2 ** k - 1) @tf.custom_gradient def _quantize(x): return tf.round(x * n) / n, lambda dy: dy return _quantize(x) def fw(x): if bitW == 32: ...
[ "\n Return the three quantization functions fw, fa, fg, for weights, activations and gradients respectively\n " ]
Please provide a description of the function:def ternarize(x, thresh=0.05): shape = x.get_shape() thre_x = tf.stop_gradient(tf.reduce_max(tf.abs(x)) * thresh) w_p = tf.get_variable('Wp', initializer=1.0, dtype=tf.float32) w_n = tf.get_variable('Wn', initializer=1.0, dtype=tf.float32) tf.summ...
[ "\n Implemented Trained Ternary Quantization:\n https://arxiv.org/abs/1612.01064\n\n Code modified from the authors' at:\n https://github.com/czhu95/ternarynet/blob/master/examples/Ternary-Net/ternary.py\n " ]
Please provide a description of the function:def interactive_imshow(img, lclick_cb=None, rclick_cb=None, **kwargs): name = 'tensorpack_viz_window' cv2.imshow(name, img) def mouse_cb(event, x, y, *args): if event == cv2.EVENT_LBUTTONUP and lclick_cb is not None: lclick_cb(img, x, y)...
[ "\n Args:\n img (np.ndarray): an image (expect BGR) to show.\n lclick_cb, rclick_cb: a callback ``func(img, x, y)`` for left/right click event.\n kwargs: can be {key_cb_a: callback_img, key_cb_b: callback_img}, to\n specify a callback ``func(img)`` for keypress.\n\n Some existi...
Please provide a description of the function:def stack_patches( patch_list, nr_row, nr_col, border=None, pad=False, bgcolor=255, viz=False, lclick_cb=None): if pad: patch_list = _pad_patch_list(patch_list, bgcolor) patch_list = _preprocess_patch_list(patch_list) if lclick_cb is...
[ "\n Stacked patches into grid, to produce visualizations like the following:\n\n .. image:: https://github.com/tensorpack/tensorpack/raw/master/examples/GAN/demo/BEGAN-CelebA-samples.jpg\n\n Args:\n patch_list(list[ndarray] or ndarray): NHW or NHWC images in [0,255].\n nr_row(int), nr_col(int...
Please provide a description of the function:def gen_stack_patches(patch_list, nr_row=None, nr_col=None, border=None, max_width=1000, max_height=1000, bgcolor=255, viz=False, lclick_cb=None): # setup parameters patch_list = _preprocess_patch...
[ "\n Similar to :func:`stack_patches` but with a generator interface.\n It takes a much-longer list and yields stacked results one by one.\n For example, if ``patch_list`` contains 1000 images and ``nr_row==nr_col==10``,\n this generator yields 10 stacked images.\n\n Args:\n nr_row(int), nr_col...
Please provide a description of the function:def dump_dataflow_images(df, index=0, batched=True, number=1000, output_dir=None, scale=1, resize=None, viz=None, flipRGB=False): if output_dir: mkdir_p(output_dir) if viz is not ...
[ "\n Dump or visualize images of a :class:`DataFlow`.\n\n Args:\n df (DataFlow): the DataFlow.\n index (int): the index of the image component.\n batched (bool): whether the component contains batched images (NHW or\n NHWC) or not (HW or HWC).\n number (int): how many dat...
Please provide a description of the function:def intensity_to_rgb(intensity, cmap='cubehelix', normalize=False): assert intensity.ndim == 2, intensity.shape intensity = intensity.astype("float") if normalize: intensity -= intensity.min() intensity /= intensity.max() cmap = plt.get...
[ "\n Convert a 1-channel matrix of intensities to an RGB image employing a colormap.\n This function requires matplotlib. See `matplotlib colormaps\n <http://matplotlib.org/examples/color/colormaps_reference.html>`_ for a\n list of available colormap.\n\n Args:\n intensity (np.ndarray): array o...
Please provide a description of the function:def draw_text(img, pos, text, color, font_scale=0.4): img = img.astype(np.uint8) x0, y0 = int(pos[0]), int(pos[1]) # Compute text size. font = cv2.FONT_HERSHEY_SIMPLEX ((text_w, text_h), _) = cv2.getTextSize(text, font, font_scale, 1) # Place tex...
[ "\n Draw text on an image.\n\n Args:\n pos (tuple): x, y; the position of the text\n text (str):\n font_scale (float):\n color (tuple): a 3-tuple BGR color in [0, 255]\n " ]
Please provide a description of the function:def draw_boxes(im, boxes, labels=None, color=None): boxes = np.asarray(boxes, dtype='int32') if labels is not None: assert len(labels) == len(boxes), "{} != {}".format(len(labels), len(boxes)) areas = (boxes[:, 2] - boxes[:, 0] + 1) * (boxes[:, 3] - ...
[ "\n Args:\n im (np.ndarray): a BGR image in range [0,255]. It will not be modified.\n boxes (np.ndarray): a numpy array of shape Nx4 where each row is [x1, y1, x2, y2].\n labels: (list[str] or None)\n color: a 3-tuple BGR color (in range [0, 255])\n\n Returns:\n np.ndarray: ...
Please provide a description of the function:def ConcatWith(x, tensor, dim): if type(tensor) != list: tensor = [tensor] return tf.concat([x] + tensor, dim)
[ "\n A wrapper around ``tf.concat`` to cooperate with :class:`LinearWrap`.\n\n Args:\n x (tf.Tensor): input\n tensor (list[tf.Tensor]): a tensor or list of tensors to concatenate with x.\n x will be at the beginning\n dim (int): the dimension along which to concatenate\n\n Re...
Please provide a description of the function:def point8_to_box(points): p = points.reshape((-1, 4, 2)) minxy = p.min(axis=1) # nx2 maxxy = p.max(axis=1) # nx2 return np.concatenate((minxy, maxxy), axis=1)
[ "\n Args:\n points: (nx4)x2\n Returns:\n nx4 boxes (x1y1x2y2)\n " ]
Please provide a description of the function:def segmentation_to_mask(polys, height, width): polys = [p.flatten().tolist() for p in polys] assert len(polys) > 0, "Polygons are empty!" import pycocotools.mask as cocomask rles = cocomask.frPyObjects(polys, height, width) rle = cocomask.merge(rle...
[ "\n Convert polygons to binary masks.\n\n Args:\n polys: a list of nx2 float array. Each array contains many (x, y) coordinates.\n\n Returns:\n a binary matrix of (height, width)\n " ]
Please provide a description of the function:def clip_boxes(boxes, shape): orig_shape = boxes.shape boxes = boxes.reshape([-1, 4]) h, w = shape boxes[:, [0, 1]] = np.maximum(boxes[:, [0, 1]], 0) boxes[:, 2] = np.minimum(boxes[:, 2], w) boxes[:, 3] = np.minimum(boxes[:, 3], h) return box...
[ "\n Args:\n boxes: (...)x4, float\n shape: h, w\n " ]
Please provide a description of the function:def filter_boxes_inside_shape(boxes, shape): assert boxes.ndim == 2, boxes.shape assert len(shape) == 2, shape h, w = shape indices = np.where( (boxes[:, 0] >= 0) & (boxes[:, 1] >= 0) & (boxes[:, 2] <= w) & (boxes[:, 3] <=...
[ "\n Args:\n boxes: (nx4), float\n shape: (h, w)\n\n Returns:\n indices: (k, )\n selection: (kx4)\n " ]
Please provide a description of the function:def MaxPooling( inputs, pool_size, strides=None, padding='valid', data_format='channels_last'): if strides is None: strides = pool_size layer = tf.layers.MaxPooling2D(pool_size, strides, padding=padding, data_forma...
[ "\n Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size.\n " ]
Please provide a description of the function:def AvgPooling( inputs, pool_size, strides=None, padding='valid', data_format='channels_last'): if strides is None: strides = pool_size layer = tf.layers.AveragePooling2D(pool_size, strides, padding=padding, data_f...
[ "\n Same as `tf.layers.AveragePooling2D`. Default strides is equal to pool_size.\n " ]
Please provide a description of the function:def GlobalAvgPooling(x, data_format='channels_last'): assert x.shape.ndims == 4 data_format = get_data_format(data_format) axis = [1, 2] if data_format == 'channels_last' else [2, 3] return tf.reduce_mean(x, axis, name='output')
[ "\n Global average pooling as in the paper `Network In Network\n <http://arxiv.org/abs/1312.4400>`_.\n\n Args:\n x (tf.Tensor): a 4D tensor.\n\n Returns:\n tf.Tensor: a NC tensor named ``output``.\n " ]
Please provide a description of the function:def FixedUnPooling(x, shape, unpool_mat=None, data_format='channels_last'): data_format = get_data_format(data_format, keras_mode=False) shape = shape2d(shape) output_shape = StaticDynamicShape(x) output_shape.apply(1 if data_format == 'NHWC' else 2, la...
[ "\n Unpool the input with a fixed matrix to perform kronecker product with.\n\n Args:\n x (tf.Tensor): a 4D image tensor\n shape: int or (h, w) tuple\n unpool_mat: a tf.Tensor or np.ndarray 2D matrix with size=shape.\n If is None, will use a matrix with 1 at top-left corner.\n\...
Please provide a description of the function:def get_savename_from_varname( varname, varname_prefix=None, savename_prefix=None): name = varname if varname_prefix is not None \ and name.startswith(varname_prefix): name = name[len(varname_prefix) + 1:] if savename_pref...
[ "\n Args:\n varname(str): a variable name in the graph\n varname_prefix(str): an optional prefix that may need to be removed in varname\n savename_prefix(str): an optional prefix to append to all savename\n Returns:\n str: the name used to save the variable\n " ]
Please provide a description of the function:def dump_session_params(path): # save variables that are GLOBAL, and either TRAINABLE or MODEL var = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) var.extend(tf.get_collection(tf.GraphKeys.MODEL_VARIABLES)) # TODO dedup assert len(set(var)) == ...
[ "\n Dump value of all TRAINABLE + MODEL variables to a dict, and save as\n npz format (loadable by :func:`sessinit.get_model_loader`).\n\n Args:\n path(str): the file name to save the parameters. Must ends with npz.\n " ]
Please provide a description of the function:def save_chkpt_vars(dic, path): logger.info("Variables to save to {}:".format(path)) keys = sorted(list(dic.keys())) logger.info(pprint.pformat(keys)) assert not path.endswith('.npy') if path.endswith('.npz'): np.savez_compressed(path, **dic...
[ "\n Save variables in dic to path.\n\n Args:\n dic: {name: value}\n path: save as npz if the name ends with '.npz', otherwise save as a checkpoint.\n " ]
Please provide a description of the function:def get_checkpoint_path(model_path): if os.path.basename(model_path) == model_path: model_path = os.path.join('.', model_path) # avoid #4921 and #6142 if os.path.basename(model_path) == 'checkpoint': assert tfv1.gfile.Exists(model_path), model_p...
[ "\n Work around TF problems in checkpoint path handling.\n\n Args:\n model_path: a user-input path\n Returns:\n str: the argument that can be passed to NewCheckpointReader\n " ]
Please provide a description of the function:def load_chkpt_vars(model_path): model_path = get_checkpoint_path(model_path) reader = tfv1.train.NewCheckpointReader(model_path) var_names = reader.get_variable_to_shape_map().keys() result = {} for n in var_names: result[n] = reader.get_ten...
[ " Load all variables from a checkpoint to a dict.\n\n Args:\n model_path(str): path to a checkpoint.\n\n Returns:\n dict: a name:value dict\n " ]
Please provide a description of the function:def is_training_name(name): # TODO: maybe simply check against TRAINABLE_VARIABLES and MODEL_VARIABLES? # TODO or use get_slot_names() name = get_op_tensor_name(name)[0] if name.endswith('/Adam') or name.endswith('/Adam_1'): return True if na...
[ "\n **Guess** if this variable is only used in training.\n Only used internally to avoid too many logging. Do not use it.\n " ]
Please provide a description of the function:def relaxed_value_for_var(value, var): assert isinstance(var, tf.Variable) name = var.op.name # check incompatible shape varshape = tuple(var.get_shape().as_list()) if varshape != value.shape: # TODO only allow re...
[ "\n Returns a relaxed (possibly reshaped/upcast-ed) version of value,\n to be loaded to the given variable.\n\n Args:\n value (ndarray): an numpy array to be loaded to var\n var (tf.Variable):\n\n Returns:\n ndarray: a possibly reshaped or casted version ...
Please provide a description of the function:def update(self, prms): with self.sess.as_default(): fetches = [] feeds = {} for name, value in six.iteritems(prms): assert name in self.name_map var = self.name_map[name] fe...
[ "\n Args:\n prms(dict): dict of {variable name: value}\n Any name in prms must be in the graph and in vars_to_update.\n " ]
Please provide a description of the function:def get_distributed_session_creator(server): server_def = server.server_def is_chief = (server_def.job_name == 'worker') and (server_def.task_index == 0) init_op = tf.global_variables_initializer() local_init_op = tf.local_variables_initializer() r...
[ "\n Args:\n server (tf.train.Server):\n\n Returns:\n tf.train.SessionCreator\n " ]
Please provide a description of the function:def get_num_gpu(): def warn_return(ret, message): try: import tensorflow as tf except ImportError: return ret built_with_cuda = tf.test.is_built_with_cuda() if not built_with_cuda and ret > 0: log...
[ "\n Returns:\n int: #available GPUs in CUDA_VISIBLE_DEVICES, or in the system.\n " ]
Please provide a description of the function:def put_summary(self, summary): if isinstance(summary, six.binary_type): summary = tf.Summary.FromString(summary) assert isinstance(summary, tf.Summary), type(summary) # TODO other types for val in summary.value: ...
[ "\n Put a `tf.Summary`.\n " ]
Please provide a description of the function:def put_scalar(self, name, val): if isinstance(val, np.floating): val = float(val) if isinstance(val, np.integer): val = int(val) self._dispatch(lambda m: m.process_scalar(name, val)) s = create_scalar_summary(...
[ "\n Put a scalar.\n " ]
Please provide a description of the function:def put_image(self, name, val): assert isinstance(val, np.ndarray) arr = image_to_nhwc(val) self._dispatch(lambda m: m.process_image(name, arr)) s = create_image_summary(name, arr) self._dispatch(lambda m: m.process_summary(s)...
[ "\n Put an image.\n\n Args:\n name (str):\n val (np.ndarray): 2D, 3D (HWC) or 4D (NHWC) numpy array of images\n in range [0,255]. If channel is 3, assumed to be RGB.\n " ]
Please provide a description of the function:def put_event(self, evt): evt.step = self.global_step evt.wall_time = time.time() self._dispatch(lambda m: m.process_event(evt))
[ "\n Put an :class:`tf.Event`.\n `step` and `wall_time` fields of :class:`tf.Event` will be filled automatically.\n\n Args:\n evt (tf.Event):\n " ]
Please provide a description of the function:def load_existing_json(): dir = logger.get_logger_dir() fname = os.path.join(dir, JSONWriter.FILENAME) if tf.gfile.Exists(fname): with open(fname) as f: stats = json.load(f) assert isinstance(stats,...
[ "\n Look for an existing json under :meth:`logger.get_logger_dir()` named \"stats.json\",\n and return the loaded list of statistics if found. Returns None otherwise.\n " ]
Please provide a description of the function:def _trigger(self): if len(self._stat_now): self._stat_now['epoch_num'] = self.epoch_num self._stat_now['global_step'] = self.global_step self._stats.append(self._stat_now) self._stat_now = {} self...
[ "\n Add stats to json and dump to disk.\n Note that this method is idempotent.\n " ]
Please provide a description of the function:def sample(img, coords): shape = img.get_shape().as_list()[1:] # h, w, c batch = tf.shape(img)[0] shape2 = coords.get_shape().as_list()[1:3] # h2, w2 assert None not in shape2, coords.get_shape() max_coor = tf.constant([shape[0] - 1, shape[1] - 1]...
[ "\n Args:\n img: bxhxwxc\n coords: bxh2xw2x2. each coordinate is (y, x) integer.\n Out of boundary coordinates will be clipped.\n Return:\n bxh2xw2xc image\n " ]
Please provide a description of the function:def GridSample(inputs, borderMode='repeat'): image, mapping = inputs assert image.get_shape().ndims == 4 and mapping.get_shape().ndims == 4 input_shape = image.get_shape().as_list()[1:] assert None not in input_shape, \ "Images in GridSample laye...
[ "\n Sample the images using the given coordinates, by bilinear interpolation.\n This was described in the paper:\n `Spatial Transformer Networks <http://arxiv.org/abs/1506.02025>`_.\n\n This is equivalent to `torch.nn.functional.grid_sample`,\n up to some non-trivial coordinate transformation.\n\n ...
Please provide a description of the function:def enable_call_trace(): def tracer(frame, event, arg): if event == 'call': co = frame.f_code func_name = co.co_name if func_name == 'write' or func_name == 'print': # ignore write() calls from print statem...
[ " Enable trace for calls to any function. " ]
Please provide a description of the function:def apply_default_prefetch(input_source_or_dataflow, trainer): if not isinstance(input_source_or_dataflow, InputSource): # to mimic same behavior of the old trainer interface if type(trainer) == SimpleTrainer: input = FeedInput(input_sour...
[ "\n Apply a set of default rules to make a fast :class:`InputSource`.\n\n Args:\n input_source_or_dataflow(InputSource | DataFlow):\n trainer (Trainer):\n\n Returns:\n InputSource\n " ]
Please provide a description of the function:def launch_train_with_config(config, trainer): if is_tfv2(): tfv1.disable_eager_execution() assert isinstance(trainer, SingleCostTrainer), trainer assert isinstance(config, TrainConfig), config assert config.model is not None assert config.d...
[ "\n Train with a :class:`TrainConfig` and a :class:`Trainer`, to\n present the simple and old training interface. It basically does the following\n 3 things (and you can easily do them by yourself if you need more control):\n\n 1. Setup the input with automatic prefetching heuristics,\n from `conf...
Please provide a description of the function:def _get_property(name): ret = property( lambda self: getattr(self.loop, name)) if six.PY3: # __doc__ is readonly in Py2 try: ret.__doc__ = getattr(TrainLoop, name).__doc__ except AttributeError: pass retur...
[ "\n Delegate property to self.loop\n " ]
Please provide a description of the function:def config(self, steps_per_epoch, starting_epoch, max_epoch): self.starting_epoch = int(starting_epoch) self.max_epoch = int(max_epoch) self.steps_per_epoch = int(steps_per_epoch) # Allow empty epoch (no steps), if we want to run the ...
[ "\n Configure the loop given the settings.\n " ]
Please provide a description of the function:def _register_callback(self, cb): if isinstance(cb, (list, tuple)): for x in cb: self._register_callback(x) return assert isinstance(cb, Callback), cb assert not isinstance(self._callbacks, Callbacks), ...
[ "\n Register callbacks to the trainer.\n It can only be called before :meth:`Trainer.train()`.\n\n Args:\n cb (Callback or [Callback]): a callback or a list of callbacks\n\n Returns:\n succeed or not\n " ]
Please provide a description of the function:def run_step(self): if not hasattr(self, 'train_op'): raise NotImplementedError( "Please either set `Trainer.train_op` or provide an implementation " "of Trainer.run_step()!") self.hooked_sess.run(self.trai...
[ "\n Defines what to do in one iteration. The default is:\n ``self.hooked_sess.run(self.train_op)``.\n\n The behavior of each iteration can be changed by either setting ``trainer.train_op``,\n or overriding this method.\n " ]
Please provide a description of the function:def setup_callbacks(self, callbacks, monitors): assert isinstance(callbacks, list), callbacks assert isinstance(monitors, list), monitors describe_trainable_vars() # TODO weird self.register_callback(MaintainStepCounter()) ...
[ "\n Setup callbacks and monitors. Must be called after the main graph is built.\n\n Args:\n callbacks ([Callback]):\n monitors ([MonitorBase]):\n " ]
Please provide a description of the function:def initialize(self, session_creator, session_init): assert isinstance(session_creator, tfv1.train.SessionCreator), session_creator assert isinstance(session_init, SessionInit), session_init session_init._setup_graph() logger.info("C...
[ "\n Create the session and set `self.sess`.\n Call `self.initiailize_hooks()`\n Finalize the graph.\n\n It must be called after callbacks are setup.\n\n Args:\n session_creator (tf.train.SessionCreator):\n session_init (sessinit.SessionInit):\n " ]
Please provide a description of the function:def initialize_hooks(self): hooks = self._callbacks.get_hooks() self.hooked_sess = tfv1.train.MonitoredSession( session_creator=ReuseSessionCreator(self.sess), hooks=hooks)
[ "\n Create SessionRunHooks for all callbacks, and hook it onto `self.sess` to create `self.hooked_sess`.\n\n A new trainer may override this method to create multiple groups of hooks,\n which can be useful when the training is not done by a single `train_op`.\n " ]
Please provide a description of the function:def main_loop(self, steps_per_epoch, starting_epoch, max_epoch): with self.sess.as_default(): self.loop.config(steps_per_epoch, starting_epoch, max_epoch) self.loop.update_global_step() try: self._callbacks...
[ "\n Run the main training loop.\n\n Args:\n steps_per_epoch, starting_epoch, max_epoch (int):\n " ]
Please provide a description of the function:def train(self, callbacks, monitors, session_creator, session_init, steps_per_epoch, starting_epoch=1, max_epoch=9999999): self.setup_callbacks(callbacks, monitors) self.initialize(session_creator, session_in...
[ "\n Implemented by three lines:\n\n .. code-block:: python\n\n self.setup_callbacks(callbacks, monitors)\n self.initialize(session_creator, session_init)\n self.main_loop(steps_per_epoch, starting_epoch, max_epoch)\n\n You can call those methods by yourself to h...
Please provide a description of the function:def train_with_defaults( self, _sentinel=None, callbacks=None, monitors=None, session_creator=None, session_init=None, steps_per_epoch=None, starting_epoch=1, max_epoch=9999999, extra_callbacks=None): ...
[ "\n Same as :meth:`train()`, except:\n\n 1. Add `extra_callbacks` to callbacks. The default value for\n `extra_callbacks` is :meth:`DEFAULT_CALLBACKS()`.\n 2. Default value for `monitors` is :meth:`DEFAULT_MONITORS()`.\n 3. Provide default values for every option except `steps_...
Please provide a description of the function:def get_default_sess_config(mem_fraction=0.99): conf = tfv1.ConfigProto() conf.allow_soft_placement = True # conf.log_device_placement = True conf.intra_op_parallelism_threads = 1 conf.inter_op_parallelism_threads = 0 # TF benchmark use cpu_cou...
[ "\n Return a tf.ConfigProto to use as default session config.\n You can modify the returned config to fit your needs.\n\n Args:\n mem_fraction(float): see the `per_process_gpu_memory_fraction` option\n in TensorFlow's GPUOptions protobuf:\n https://github.com/tensorflow/tensorf...
Please provide a description of the function:def get_global_step_var(): scope = tfv1.VariableScope(reuse=False, name='') # the root vs with tfv1.variable_scope(scope): var = tfv1.train.get_or_create_global_step() return var
[ "\n Returns:\n tf.Tensor: the global_step variable in the current graph. Create if doesn't exist.\n " ]
Please provide a description of the function:def get_tensors_by_names(names): ret = [] G = tfv1.get_default_graph() for n in names: opn, varn = get_op_tensor_name(n) ret.append(G.get_tensor_by_name(varn)) return ret
[ "\n Get a list of tensors in the default graph by a list of names.\n\n Args:\n names (list):\n " ]
Please provide a description of the function:def get_op_or_tensor_by_name(name): G = tfv1.get_default_graph() def f(n): if len(n) >= 3 and n[-2] == ':': return G.get_tensor_by_name(n) else: return G.get_operation_by_name(n) if not isinstance(name, list): ...
[ "\n Get either tf.Operation of tf.Tensor from names.\n\n Args:\n name (list[str] or str): names of operations or tensors.\n\n Raises:\n KeyError, if the name doesn't exist\n " ]
Please provide a description of the function:def _add_sync_queues_and_barrier(self, name, dependencies): self._sync_queue_counter += 1 with tf.device(self.sync_queue_devices[self._sync_queue_counter % len(self.sync_queue_devices)]): sync_queues = [ tf.FIFOQueue(self....
[ "Adds ops to enqueue on all worker queues.\n\n Args:\n name: prefixed for the shared_name of ops.\n dependencies: control dependency from ops.\n\n Returns:\n an op that should be used as control dependency before starting next step.\n " ]
Please provide a description of the function:def _apply_shadow_vars(avg_grads): ps_var_grads = [] for grad, var in avg_grads: assert var.name.startswith('tower'), var.name my_name = '/'.join(var.name.split('/')[1:]) my_name = get_op_tensor_name(my_name)[0] ...
[ "\n Create shadow variables on PS, and replace variables in avg_grads\n by these shadow variables.\n\n Args:\n avg_grads: list of (grad, var) tuples\n " ]
Please provide a description of the function:def _shadow_model_variables(shadow_vars): G = tf.get_default_graph() curr_shadow_vars = set([v.name for v in shadow_vars]) model_vars = tf.model_variables() shadow_model_vars = [] for v in model_vars: assert v.name...
[ "\n Create shadow vars for model_variables as well, and add to the list of ``shadow_vars``.\n\n Returns:\n list of (shadow_model_var, local_model_var) used for syncing.\n " ]
Please provide a description of the function:def build(self, get_grad_fn, get_opt_fn): with override_to_local_variable(): get_global_step_var() get_opt_fn = memoized(get_opt_fn) # Build the optimizer first, before entering any tower. # This makes sure that learning_...
[ "\n Args:\n get_grad_fn (-> [(grad, var)]):\n get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer\n\n Returns:\n (tf.Operation, tf.Operation, tf.Operation):\n\n 1. the training op.\n\n 2. the op which sync all the local variabl...
Please provide a description of the function:def _apply_gradients_and_copy(self, opt, raw_grad_list, ps_var_grads): # TODO do this for variables together? with tf.name_scope('apply_gradients'): var_update_ops = [] for vid, (g, v) in enumerate(ps_var_grads): ...
[ "\n Apply averaged gradients to ps vars, and then copy the updated\n variables back to each tower.\n\n Args:\n raw_grad_list: Ngpu x Nvar x 2 gradient list from all towers\n ps_var_grads: Nvar x 2 (grad, ps_var)\n\n Returns:\n list of copy ops\n " ...
Please provide a description of the function:def _get_initial_sync_op(self): def strip_port(s): if s.endswith(':0'): return s[:-2] return s local_vars = tf.local_variables() local_var_by_name = dict([(strip_port(v.name), v) for v in local_vars]) ...
[ "\n Get the op to copy-initialized all local variables from PS.\n " ]
Please provide a description of the function:def _get_sync_model_vars_op(self): ops = [] for (shadow_v, local_v) in self._shadow_model_vars: ops.append(shadow_v.assign(local_v.read_value())) assert len(ops) return tf.group(*ops, name='sync_{}_model_variables_to_ps'.f...
[ "\n Get the op to sync local model_variables to PS.\n " ]
Please provide a description of the function:def get_tensors_inputs(placeholders, tensors, names): assert len(tensors) == len(names), \ "Input tensors {} and input names {} have different length!".format( tensors, names) ret = copy.copy(placeholders) placeholder_names = [p.name for ...
[ "\n Args:\n placeholders (list[Tensor]):\n tensors (list[Tensor]): list of tf.Tensor\n names (list[str]): names matching the given tensors\n\n Returns:\n list[Tensor]: inputs to used for the tower function,\n with the corresponding placeholders replaced by tensors.\n ...
Please provide a description of the function:def get_sublist_by_names(lst, names): orig_names = [p.name for p in lst] ret = [] for name in names: try: idx = orig_names.index(name) except ValueError: logger.error("Name {} doesn't appear in lst {}!".format( ...
[ "\n Args:\n lst (list): list of objects with \"name\" property.\n\n Returns:\n list: a sublist of objects, matching names\n " ]
Please provide a description of the function:def remap_input_source(input, names): def __init__(self, input, names): ProxyInputSource.__init__(self, input) assert isinstance(names, (list, tuple)), names self._names = tuple(names) def _setup(self, inputs): self._all_placehdr...
[ "\n When you have some :class:`InputSource` which doesn't match the inputs of\n your tower function, use `RemapInputSource`.\n It produces placeholders for all the inputs in your model,\n except that the corresponding ones are replaced with the tensor produced\n by the given :class:`InputSource`.\n\n...
Please provide a description of the function:def rpn_head(featuremap, channel, num_anchors): with argscope(Conv2D, data_format='channels_first', kernel_initializer=tf.random_normal_initializer(stddev=0.01)): hidden = Conv2D('conv0', featuremap, channel, 3, activation=tf.nn.relu) ...
[ "\n Returns:\n label_logits: fHxfWxNA\n box_logits: fHxfWxNAx4\n " ]
Please provide a description of the function:def rpn_losses(anchor_labels, anchor_boxes, label_logits, box_logits): with tf.device('/cpu:0'): valid_mask = tf.stop_gradient(tf.not_equal(anchor_labels, -1)) pos_mask = tf.stop_gradient(tf.equal(anchor_labels, 1)) nr_valid = tf.stop_gradien...
[ "\n Args:\n anchor_labels: fHxfWxNA\n anchor_boxes: fHxfWxNAx4, encoded\n label_logits: fHxfWxNA\n box_logits: fHxfWxNAx4\n\n Returns:\n label_loss, box_loss\n " ]
Please provide a description of the function:def generate_rpn_proposals(boxes, scores, img_shape, pre_nms_topk, post_nms_topk=None): assert boxes.shape.ndims == 2, boxes.shape if post_nms_topk is None: post_nms_topk = pre_nms_topk topk = tf.minimum(pre_nms_topk, tf.s...
[ "\n Sample RPN proposals by the following steps:\n 1. Pick top k1 by scores\n 2. NMS them\n 3. Pick top k2 by scores. Default k2 == k1, i.e. does not filter the NMS output.\n\n Args:\n boxes: nx4 float dtype, the proposal boxes. Decoded to floatbox already\n scores: n float, the logits\...
Please provide a description of the function:def MergeAllSummaries(period=0, run_alone=False, key=None): if key is None: key = tf.GraphKeys.SUMMARIES period = int(period) if run_alone: return MergeAllSummaries_RunAlone(period, key) else: return MergeAllSummaries_RunWithOp(pe...
[ "\n This callback is enabled by default.\n Evaluate all summaries by ``tf.summary.merge_all``, and write them to logs.\n\n Args:\n period (int): by default the callback summarizes once every epoch.\n This option (if not set to 0) makes it additionally summarize every ``period`` steps.\n ...
Please provide a description of the function:def append(self, exp): if self._curr_size < self.max_size: self._assign(self._curr_pos, exp) self._curr_pos = (self._curr_pos + 1) % self.max_size self._curr_size += 1 else: self._assign(self._curr_pos,...
[ "\n Args:\n exp (Experience):\n " ]
Please provide a description of the function:def sample(self, idx): idx = (self._curr_pos + idx) % self._curr_size k = self.history_len + 1 if idx + k <= self._curr_size: state = self.state[idx: idx + k] reward = self.reward[idx: idx + k] action = sel...
[ " return a tuple of (s,r,a,o),\n where s is of shape self._output_shape, which is\n [H, W, (hist_len+1) * channel] if input is (H, W, channel)" ]
Please provide a description of the function:def step(self, exploration): old_s = self._current_ob if self.rng.rand() <= exploration: act = self.rng.choice(range(self.num_actions)) else: history = self.recent_state() history.append(old_s) ...
[ "\n Run the environment for one step.\n If the episode ends, store the entire episode to the replay memory.\n " ]
Please provide a description of the function:def recent_state(self): expected_len = self.history_len - 1 if len(self._current_episode) >= expected_len: return [k.state for k in self._current_episode[-expected_len:]] else: states = [np.zeros(self.state_shape, dtyp...
[ "\n Get the recent state (with stacked history) of the environment.\n\n Returns:\n a list of ``hist_len-1`` elements, each of shape ``self.state_shape``\n " ]
Please provide a description of the function:def step(self, exploration): if len(self._runners) > 1: self._populate_job_queue.put(exploration) else: self._runners[0].step(exploration)
[ "\n Execute one step in any of the runners.\n " ]
Please provide a description of the function:def reset_stats(self): scores = list(itertools.chain.from_iterable([v.total_scores for v in self._runners])) for v in self._runners: v.total_scores.clear() try: return np.mean(scores), np.max(scores) except Ex...
[ "\n Returns:\n mean, max: two stats of the runners, to be added to backend\n " ]
Please provide a description of the function:def log(self): if self.tot < 3: return msgs = [] for name, t in self.times: if t / self.tot > 0.3 and t > 1: msgs.append(name + ": " + humanize_time_delta(t)) logger.info( "Callback...
[ " log the time of some heavy callbacks " ]
Please provide a description of the function:def TowerContext(tower_name, is_training, vs_name=''): if is_training: return TrainTowerContext(tower_name, vs_name=vs_name) else: return PredictTowerContext(tower_name, vs_name=vs_name)
[ "\n The context for a tower function, containing metadata about the current tower.\n Tensorpack trainers use :class:`TowerContext` to manage tower function.\n Many tensorpack layers have to be called under a :class:`TowerContext`.\n\n Example:\n\n .. code-block:: python\n\n with TowerContext('...
Please provide a description of the function:def training(self): handles = [h for h in self._handles if h.is_training] return TowerTensorHandles(handles)
[ "\n Returns:\n A :class:`TowerTensorHandles`, containing only the training towers.\n " ]
Please provide a description of the function:def inference(self): handles = [h for h in self._handles if not h.is_training] return TowerTensorHandles(handles)
[ "\n Returns:\n A :class:`TowerTensorHandles`, containing only the inference towers.\n " ]
Please provide a description of the function:def get_tensor(self, name): name = get_op_tensor_name(name)[1] if len(self.ns_name): name_with_ns = self.ns_name + "/" + name else: name_with_ns = name try: ret = get_op_or_tensor_by_name(name_with...
[ "\n Get a tensor in this tower. The name can be:\n\n 1. The name of the tensor without any tower prefix.\n\n 2. A name in the input signature, if it is used when building the tower.\n\n In the second case, this method will return the tensor that's used as the corresponding\n input...
Please provide a description of the function:def get_variable(self, name): name = get_op_tensor_name(name)[1] if len(self.vs_name): name_with_vs = self.vs_name + "/" + name else: name_with_vs = name return get_op_or_tensor_by_name(name_with_vs)
[ "\n Get a variable used in this tower.\n The name should not contain the variable scope prefix of the tower.\n\n When the tower has the same variable scope and name scope, this is equivalent to\n :meth:`get_tensor`.\n " ]
Please provide a description of the function:def get_collection(self, key=None, name=None): if name is not None: logger.warn("TowerTensorHandle.get_collection(name=..) was renamed to (key=..) !") key = name return self._ctx.get_collection_in_tower(key)
[ "\n See :meth:`BaseTowerContext.get_collection_in_tower`.\n\n Args:\n key (str): the key of the collection\n name: deprecated\n " ]
Please provide a description of the function:def mkdir_p(dirname): assert dirname is not None if dirname == '' or os.path.isdir(dirname): return try: os.makedirs(dirname) except OSError as e: if e.errno != errno.EEXIST: raise e
[ " Like \"mkdir -p\", make a dir recursively, but do nothing if the dir exists\n\n Args:\n dirname(str):\n " ]
Please provide a description of the function:def download(url, dir, filename=None, expect_size=None): mkdir_p(dir) if filename is None: filename = url.split('/')[-1] fpath = os.path.join(dir, filename) if os.path.isfile(fpath): if expect_size is not None and os.stat(fpath).st_size ...
[ "\n Download URL to a directory.\n Will figure out the filename automatically from URL, if not given.\n " ]
Please provide a description of the function:def recursive_walk(rootdir): for r, dirs, files in os.walk(rootdir): for f in files: yield os.path.join(r, f)
[ "\n Yields:\n str: All files in rootdir, recursively.\n " ]
Please provide a description of the function:def get_dataset_path(*args): d = os.environ.get('TENSORPACK_DATASET', None) if d is None: d = os.path.join(os.path.expanduser('~'), 'tensorpack_data') if execute_only_once(): logger.warn("Env var $TENSORPACK_DATASET not set, using {} ...
[ "\n Get the path to some dataset under ``$TENSORPACK_DATASET``.\n\n Args:\n args: strings to be joined to form path.\n\n Returns:\n str: path to the dataset.\n " ]
Please provide a description of the function:def backup_collection(keys=None): if keys is None: keys = tf.get_default_graph().get_all_collection_keys() ret = {} assert isinstance(keys, (list, tuple, set)) for k in keys: ret[k] = copy(tf.get_collection(k)) return ret
[ "\n Args:\n keys (list): list of collection keys to backup.\n Defaults to all keys in the graph.\n\n Returns:\n dict: the backup\n " ]
Please provide a description of the function:def restore_collection(backup): for k, v in six.iteritems(backup): del tf.get_collection_ref(k)[:] tf.get_collection_ref(k).extend(v)
[ "\n Restore from a collection backup.\n\n Args:\n backup (dict):\n " ]
Please provide a description of the function:def get_collection_in_tower(self, key): new = tf.get_collection(key) old = set(self.original.get(key, [])) # persist the order in new return [x for x in new if x not in old]
[ "\n Get items from this collection that are added in the current tower.\n " ]
Please provide a description of the function:def ptb_producer(raw_data, batch_size, num_steps, name=None): with tf.name_scope(name, "PTBProducer", [raw_data, batch_size, num_steps]): raw_data = tf.convert_to_tensor(raw_data, name="raw_data", dtype=tf.int32) data_len = tf.size(raw_data) batch_len = dat...
[ "Iterate on the raw PTB data.\n\n This chunks up raw_data into batches of examples and returns Tensors that\n are drawn from these batches.\n\n Args:\n raw_data: one of the raw data outputs from ptb_raw_data.\n batch_size: int, the batch size.\n num_steps: int, the number of unrolls.\n name: the name...
Please provide a description of the function:def set_logger_dir(dirname, action=None): global LOG_DIR, _FILE_HANDLER if _FILE_HANDLER: # unload and close the old file handler, so that we may safely delete the logger directory _logger.removeHandler(_FILE_HANDLER) del _FILE_HANDLER ...
[ "\n Set the directory for global logging.\n\n Args:\n dirname(str): log directory\n action(str): an action of [\"k\",\"d\",\"q\"] to be performed\n when the directory exists. Will ask user by default.\n\n \"d\": delete the directory. Note that the deletion may fail when...
Please provide a description of the function:def auto_set_dir(action=None, name=None): mod = sys.modules['__main__'] basename = os.path.basename(mod.__file__) auto_dirname = os.path.join('train_log', basename[:basename.rfind('.')]) if name: auto_dirname += '_%s' % name if os.name == 'nt' el...
[ "\n Use :func:`logger.set_logger_dir` to set log directory to\n \"./train_log/{scriptname}:{name}\". \"scriptname\" is the name of the main python file currently running" ]
Please provide a description of the function:def class_balanced_sigmoid_cross_entropy(logits, label, name='cross_entropy_loss'): with tf.name_scope('class_balanced_sigmoid_cross_entropy'): y = tf.cast(label, tf.float32) count_neg = tf.reduce_sum(1. - y) count_pos = tf.reduce_sum(y) ...
[ "\n The class-balanced cross entropy loss,\n as in `Holistically-Nested Edge Detection\n <http://arxiv.org/abs/1504.06375>`_.\n\n Args:\n logits: of shape (b, ...).\n label: of the same shape. the ground truth in {0,1}.\n Returns:\n class-balanced cross entropy loss.\n " ]
Please provide a description of the function:def CaffeBilinearUpSample(x, shape): inp_shape = x.shape.as_list() ch = inp_shape[1] assert ch == 1, "This layer only works for channel=1" # for a version that supports >1 channels, see: # https://github.com/tensorpack/tensorpack/issues/1040#issuecom...
[ "\n Deterministic bilinearly-upsample the input images.\n It is implemented by deconvolution with \"BilinearFiller\" in Caffe.\n It is aimed to mimic caffe behavior.\n\n Args:\n x (tf.Tensor): a NCHW tensor\n shape (int): the upsample factor\n\n Returns:\n tf.Tensor: a NCHW tenso...
Please provide a description of the function:def reset_state(self): assert not self._reset_done, "reset_state() was called twice! This violates the API of DataFlow!" self._reset_done = True # __del__ not guaranteed to get called at exit atexit.register(del_weakref, weakref.ref(...
[ "\n All forked dataflows should only be reset **once and only once** in spawned processes.\n Subclasses should call this method with super.\n " ]
Please provide a description of the function:def is_compatible_with(self, spec_or_tensor): return (self._dtype.is_compatible_with(spec_or_tensor.dtype) and self._shape.is_compatible_with(spec_or_tensor.shape))
[ "Returns True if spec_or_tensor is compatible with this TensorSpec.\n\n Two tensors are considered compatible if they have the same dtype\n and their shapes are compatible (see `tf.TensorShape.is_compatible_with`).\n\n Args:\n spec_or_tensor: A tf.TensorSpec or a tf.Tensor\n\n Returns:\n True ...