INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Return the directory structure of "dir". Args: dir(str): something like '/path/to/imagenet/val' Returns: either 'train' or 'original'
def guess_dir_structure(dir): """ Return the directory structure of "dir". Args: dir(str): something like '/path/to/imagenet/val' Returns: either 'train' or 'original' """ subdir = os.listdir(dir)[0] # find a subdir starting with 'n' ...
Args: json_file (str): path to the results json file in coco format Returns: dict: the evaluation metrics
def print_coco_metrics(self, json_file): """ Args: json_file (str): path to the results json file in coco format Returns: dict: the evaluation metrics """ from pycocotools.cocoeval import COCOeval ret = {} cocoDt = self.coco.loadRes(json_fi...
Args: add_gt: whether to add ground truth bounding box annotations to the dicts add_mask: whether to also add ground truth mask Returns: a list of dict, each has keys including: 'image_id', 'file_name', and (if add_gt is True) 'boxes', 'class'...
def load(self, add_gt=True, add_mask=False): """ Args: add_gt: whether to add ground truth bounding box annotations to the dicts add_mask: whether to also add ground truth mask Returns: a list of dict, each has keys including: 'image_id', 'fil...
Change relative filename to abosolute file name.
def _use_absolute_file_name(self, img): """ Change relative filename to abosolute file name. """ img['file_name'] = os.path.join( self._imgdir, img['file_name']) assert os.path.isfile(img['file_name']), img['file_name']
Add 'boxes', 'class', 'is_crowd' of this image to the dict, used by detection. If add_mask is True, also add 'segmentation' in coco poly format.
def _add_detection_gt(self, img, add_mask): """ Add 'boxes', 'class', 'is_crowd' of this image to the dict, used by detection. If add_mask is True, also add 'segmentation' in coco poly format. """ # ann_ids = self.coco.getAnnIds(imgIds=img['image_id']) # objs = self.coco....
Load and merges several instance files together. Returns the same format as :meth:`COCODetection.load`.
def load_many(basedir, names, add_gt=True, add_mask=False): """ Load and merges several instance files together. Returns the same format as :meth:`COCODetection.load`. """ if not isinstance(names, (list, tuple)): names = [names] ret = [] for n in name...
Args: names (list[str]): name of the training datasets, e.g. ['train2014', 'valminusminival2014'] Returns: roidbs (list[dict]): Produce "roidbs" as a list of dict, each dict corresponds to one image with k>=0 instances. and the following keys are expected for training:...
def load_training_roidbs(self, names): """ Args: names (list[str]): name of the training datasets, e.g. ['train2014', 'valminusminival2014'] Returns: roidbs (list[dict]): Produce "roidbs" as a list of dict, each dict corresponds to one image with k>=0 instances...
Args: name (str): name of one inference dataset, e.g. 'minival2014' Returns: roidbs (list[dict]): Each dict corresponds to one image to run inference on. The following keys in the dict are expected: file_name (str): full path to the image ...
def load_inference_roidbs(self, name): """ Args: name (str): name of one inference dataset, e.g. 'minival2014' Returns: roidbs (list[dict]): Each dict corresponds to one image to run inference on. The following keys in the dict are expected: ...
Args: results (list[dict]): the inference results as dicts. Each dict corresponds to one __instance__. It contains the following keys: image_id (str): the id that matches `load_inference_roidbs`. category_id (int): the category prediction, in range [1, #categ...
def eval_or_save_inference_results(self, results, dataset, output=None): """ Args: results (list[dict]): the inference results as dicts. Each dict corresponds to one __instance__. It contains the following keys: image_id (str): the id that matches `load_infer...
Surround a context with a timer. Args: msg(str): the log to print. log_start(bool): whether to print also at the beginning. Example: .. code-block:: python with timed_operation('Good Stuff'): time.sleep(1) Will print: .. code-block:: pytho...
def timed_operation(msg, log_start=False): """ Surround a context with a timer. Args: msg(str): the log to print. log_start(bool): whether to print also at the beginning. Example: .. code-block:: python with timed_operation('Good Stuff'): time.sleep...
A context which add the time spent inside to TotalTimer.
def total_timer(msg): """ A context which add the time spent inside to TotalTimer. """ start = timer() yield t = timer() - start _TOTAL_TIMER_DATA[msg].feed(t)
Print the content of the TotalTimer, if it's not empty. This function will automatically get called when program exits.
def print_total_timer(): """ Print the content of the TotalTimer, if it's not empty. This function will automatically get called when program exits. """ if len(_TOTAL_TIMER_DATA) == 0: return for k, v in six.iteritems(_TOTAL_TIMER_DATA): logger.info("Total Time: {} -> {:.2f} sec,...
Will reset state of each augmentor
def reset_state(self): """ Will reset state of each augmentor """ super(AugmentorList, self).reset_state() for a in self.augmentors: a.reset_state()
Make sure processes terminate when main process exit. Args: proc (multiprocessing.Process or list)
def ensure_proc_terminate(proc): """ Make sure processes terminate when main process exit. Args: proc (multiprocessing.Process or list) """ if isinstance(proc, list): for p in proc: ensure_proc_terminate(p) return def stop_proc_by_weak_ref(ref): proc...
Set the "death signal" of the current process, so that the current process will be cleaned with guarantee in case the parent dies accidentally.
def enable_death_signal(_warn=True): """ Set the "death signal" of the current process, so that the current process will be cleaned with guarantee in case the parent dies accidentally. """ if platform.system() != 'Linux': return try: import prctl # pip install python-prctl...
Returns: If called in main thread, returns a context where ``SIGINT`` is ignored, and yield True. Otherwise yield False.
def mask_sigint(): """ Returns: If called in main thread, returns a context where ``SIGINT`` is ignored, and yield True. Otherwise yield False. """ if is_main_thread(): sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN) yield True signal.signal(signal.S...
Start process(es) with SIGINT ignored. Args: proc: (mp.Process or list) Note: The signal mask is only applied when called from main thread.
def start_proc_mask_signal(proc): """ Start process(es) with SIGINT ignored. Args: proc: (mp.Process or list) Note: The signal mask is only applied when called from main thread. """ if not isinstance(proc, list): proc = [proc] with mask_sigint(): for p in p...
Execute a command with timeout, and return STDOUT and STDERR Args: cmd(str): the command to execute. timeout(float): timeout in seconds. Returns: output(bytes), retcode(int). If timeout, retcode is -1.
def subproc_call(cmd, timeout=None): """ Execute a command with timeout, and return STDOUT and STDERR Args: cmd(str): the command to execute. timeout(float): timeout in seconds. Returns: output(bytes), retcode(int). If timeout, retcode is -1. """ try: output = s...
Put obj to queue, but will give up when the thread is stopped
def queue_put_stoppable(self, q, obj): """ Put obj to queue, but will give up when the thread is stopped""" while not self.stopped(): try: q.put(obj, timeout=5) break except queue.Full: pass
Take obj from queue, but will give up when the thread is stopped
def queue_get_stoppable(self, q): """ Take obj from queue, but will give up when the thread is stopped""" while not self.stopped(): try: return q.get(timeout=5) except queue.Empty: pass
Args: rank(int): rank of th element. All elements must have different ranks. val: an object
def put(self, rank, val): """ Args: rank(int): rank of th element. All elements must have different ranks. val: an object """ idx = bisect.bisect(self.ranks, rank) self.ranks.insert(idx, rank) self.data.insert(idx, val)
Visualize use weights in convolution filters. Args: filters: tensor containing the weights [H,W,Cin,Cout] name: label for tensorboard Returns: image of all weight
def visualize_conv_weights(filters, name): """Visualize use weights in convolution filters. Args: filters: tensor containing the weights [H,W,Cin,Cout] name: label for tensorboard Returns: image of all weight """ with tf.name_scope('visualize_w_' + name): filters = ...
Visualize activations for convolution layers. Remarks: This tries to place all activations into a square. Args: activation: tensor with the activation [B,H,W,C] name: label for tensorboard Returns: image of almost all activations
def visualize_conv_activations(activation, name): """Visualize activations for convolution layers. Remarks: This tries to place all activations into a square. Args: activation: tensor with the activation [B,H,W,C] name: label for tensorboard Returns: image of almost al...
Make the static shape of a tensor less specific. If you want to feed to a tensor, the shape of the feed value must match the tensor's static shape. This function creates a placeholder which defaults to x if not fed, but has a less specific static shape than x. See also `tensorflow#5680 <https://github....
def shapeless_placeholder(x, axis, name): """ Make the static shape of a tensor less specific. If you want to feed to a tensor, the shape of the feed value must match the tensor's static shape. This function creates a placeholder which defaults to x if not fed, but has a less specific static shape ...
Estimate H(x|s) ~= -E_{x \sim P(x|s)}[\log Q(x|s)], where x are samples, and Q is parameterized by vec.
def entropy_from_samples(samples, vec): """ Estimate H(x|s) ~= -E_{x \sim P(x|s)}[\log Q(x|s)], where x are samples, and Q is parameterized by vec. """ samples_cat = tf.argmax(samples[:, :NUM_CLASS], axis=1, output_type=tf.int32) samples_uniform = samples[:, NUM_CLASS:] cat, uniform = get_distri...
OpenAI official code actually models the "uniform" latent code as a Gaussian distribution, but obtain the samples from a uniform distribution.
def sample_prior(batch_size): cat, _ = get_distributions(DIST_PRIOR_PARAM[:NUM_CLASS], DIST_PRIOR_PARAM[NUM_CLASS:]) sample_cat = tf.one_hot(cat.sample(batch_size), NUM_CLASS) """ OpenAI official code actually models the "uniform" latent code as a Gaussian distribution, but obtain the samples from ...
Mutual information between x (i.e. zc in this case) and some information s (the generated samples in this case): I(x;s) = H(x) - H(x|s) = H(x) + E[\log P(x|s)] The distribution from which zc is sampled, in this case, is set to a fixed prior already. ...
def build_graph(self, real_sample): real_sample = tf.expand_dims(real_sample, -1) # sample the latent code: zc = shapeless_placeholder(sample_prior(BATCH), 0, name='z_code') z_noise = shapeless_placeholder( tf.random_uniform([BATCH, NOISE_DIM], -1, 1), 0, name='z_noise') ...
see "Dynamic Filter Networks" (NIPS 2016) by Bert De Brabandere*, Xu Jia*, Tinne Tuytelaars and Luc Van Gool Remarks: This is the convolution version of a dynamic filter. Args: inputs : unfiltered input [b, h, w, 1] only grayscale images. filters : learned filters of [b, k, k, ...
def DynamicConvFilter(inputs, filters, out_channel, kernel_shape, stride=1, padding='SAME'): """ see "Dynamic Filter Networks" (NIPS 2016) by Bert De Brabandere*, Xu Jia*, Tinne Tuytelaars and Luc Van Gool Remarks: This is the co...
Estimate filters for convolution layers Args: theta: angle of filter kernel_shape: size of each filter Returns: learned filter as [B, k, k, 1]
def _parameter_net(self, theta, kernel_shape=9): """Estimate filters for convolution layers Args: theta: angle of filter kernel_shape: size of each filter Returns: learned filter as [B, k, k, 1] """ with argscope(FullyConnected, nl=tf.nn.leak...
Implements a steerable Gaussian filter. This function can be used to evaluate the first directional derivative of an image, using the method outlined in W. T. Freeman and E. H. Adelson, "The Design and Use of Steerable Filters", IEEE PAMI, 1991. It evaluates th...
def filter_with_theta(image, theta, sigma=1., filter_size=9): """Implements a steerable Gaussian filter. This function can be used to evaluate the first directional derivative of an image, using the method outlined in W. T. Freeman and E. H. Adelson, "The Design ...
Assign `self.g_vars` to the parameters under scope `g_scope`, and same with `self.d_vars`.
def collect_variables(self, g_scope='gen', d_scope='discrim'): """ Assign `self.g_vars` to the parameters under scope `g_scope`, and same with `self.d_vars`. """ self.g_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, g_scope) assert self.g_vars self.d_v...
Build standard GAN loss and set `self.g_loss` and `self.d_loss`. D and G play two-player minimax game with value function V(G,D) min_G max _D V(D, G) = IE_{x ~ p_data} [log D(x)] + IE_{z ~ p_fake} [log (1 - D(G(z)))] Args: logits_real (tf.Tensor): discrim logits from real sample...
def build_losses(self, logits_real, logits_fake): """ Build standard GAN loss and set `self.g_loss` and `self.d_loss`. D and G play two-player minimax game with value function V(G,D) min_G max _D V(D, G) = IE_{x ~ p_data} [log D(x)] + IE_{z ~ p_fake} [log (1 - D(G(z)))] Args...
We need to set tower_func because it's a TowerTrainer, and only TowerTrainer supports automatic graph creation for inference during training. If we don't care about inference during training, using tower_func is not needed. Just calling model.build_graph directly is OK.
def _build_gan_trainer(self, input, model): """ We need to set tower_func because it's a TowerTrainer, and only TowerTrainer supports automatic graph creation for inference during training. If we don't care about inference during training, using tower_func is not needed. Just ca...
After applying this decorator: 1. data_format becomes tf.layers style 2. nl becomes activation 3. initializers are renamed 4. positional args are transformed to corresponding kwargs, according to args_names 5. kwargs are mapped to tf.layers names if needed, by name_mapping
def convert_to_tflayer_args(args_names, name_mapping): """ After applying this decorator: 1. data_format becomes tf.layers style 2. nl becomes activation 3. initializers are renamed 4. positional args are transformed to corresponding kwargs, according to args_names 5. kwargs are mapped to tf...
Args: mapping(dict): an old -> new mapping for variable basename. e.g. {'kernel': 'W'} Returns: A context where the variables are renamed.
def rename_get_variable(mapping): """ Args: mapping(dict): an old -> new mapping for variable basename. e.g. {'kernel': 'W'} Returns: A context where the variables are renamed. """ def custom_getter(getter, name, *args, **kwargs): splits = name.split('/') basename = ...
Apply a regularizer on trainable variables matching the regex, and print the matched variables (only print once in multi-tower training). In replicated mode, it will only regularize variables within the current tower. If called under a TowerContext with `is_training==False`, this function returns a zero co...
def regularize_cost(regex, func, name='regularize_cost'): """ Apply a regularizer on trainable variables matching the regex, and print the matched variables (only print once in multi-tower training). In replicated mode, it will only regularize variables within the current tower. If called under a T...
Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``. If in replicated mode, will only regularize variables created within the current tower. Args: name (str): the name of the returned tensor Returns: tf.Tensor: a scalar, the total regularization cost.
def regularize_cost_from_collection(name='regularize_cost'): """ Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``. If in replicated mode, will only regularize variables created within the current tower. Args: name (str): the name of the returned tensor Returns: ...
Same as `tf.layers.dropout`. However, for historical reasons, the first positional argument is interpreted as keep_prob rather than drop_prob. Explicitly use `rate=` keyword arguments to ensure things are consistent.
def Dropout(x, *args, **kwargs): """ Same as `tf.layers.dropout`. However, for historical reasons, the first positional argument is interpreted as keep_prob rather than drop_prob. Explicitly use `rate=` keyword arguments to ensure things are consistent. """ if 'is_training' in kwargs: ...
Return a proper background image of background_shape, given img. Args: background_shape (tuple): a shape (h, w) img: an image Returns: a background image
def fill(self, background_shape, img): """ Return a proper background image of background_shape, given img. Args: background_shape (tuple): a shape (h, w) img: an image Returns: a background image """ background_shape = tuple(backgroun...
Apply a function on the wrapped tensor. Returns: LinearWrap: ``LinearWrap(func(self.tensor(), *args, **kwargs))``.
def apply(self, func, *args, **kwargs): """ Apply a function on the wrapped tensor. Returns: LinearWrap: ``LinearWrap(func(self.tensor(), *args, **kwargs))``. """ ret = func(self._t, *args, **kwargs) return LinearWrap(ret)
Apply a function on the wrapped tensor. The tensor will be the second argument of func. This is because many symbolic functions (such as tensorpack's layers) takes 'scope' as the first argument. Returns: LinearWrap: ``LinearWrap(func(args[0], self.tensor(), *args[1:], **kwa...
def apply2(self, func, *args, **kwargs): """ Apply a function on the wrapped tensor. The tensor will be the second argument of func. This is because many symbolic functions (such as tensorpack's layers) takes 'scope' as the first argument. Returns: LinearWra...
Returns: A context where the gradient of :meth:`tf.nn.relu` is replaced by guided back-propagation, as described in the paper: `Striving for Simplicity: The All Convolutional Net <https://arxiv.org/abs/1412.6806>`_
def guided_relu(): """ Returns: A context where the gradient of :meth:`tf.nn.relu` is replaced by guided back-propagation, as described in the paper: `Striving for Simplicity: The All Convolutional Net <https://arxiv.org/abs/1412.6806>`_ """ from tensorflow.python.ops imp...
Produce a saliency map as described in the paper: `Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps <https://arxiv.org/abs/1312.6034>`_. The saliency map is the gradient of the max element in output w.r.t input. Returns: tf.Tensor: the saliency map. ...
def saliency_map(output, input, name="saliency_map"): """ Produce a saliency map as described in the paper: `Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps <https://arxiv.org/abs/1312.6034>`_. The saliency map is the gradient of the max element in outpu...
A wrapper around `tf.layers.Conv2D`. Some differences to maintain backward-compatibility: 1. Default kernel initializer is variance_scaling_initializer(2.0). 2. Default padding is 'same'. 3. Support 'split' argument to do group conv. Note that this is not efficient. Variable Names: * ``W``: w...
def Conv2D( inputs, filters, kernel_size, strides=(1, 1), padding='same', data_format='channels_last', dilation_rate=(1, 1), activation=None, use_bias=True, kernel_initializer=None, bias_initializer=tf.zeros_initializer(), k...
A wrapper around `tf.layers.Conv2DTranspose`. Some differences to maintain backward-compatibility: 1. Default kernel initializer is variance_scaling_initializer(2.0). 2. Default padding is 'same' Variable Names: * ``W``: weights * ``b``: bias
def Conv2DTranspose( inputs, filters, kernel_size, strides=(1, 1), padding='same', data_format='channels_last', activation=None, use_bias=True, kernel_initializer=None, bias_initializer=tf.zeros_initializer(), kernel_regularizer=Non...
Will setup the assign operator for that variable.
def setup_graph(self): """ Will setup the assign operator for that variable. """ all_vars = tfv1.global_variables() + tfv1.local_variables() for v in all_vars: if v.name == self.var_name: self.var = v break else: raise ValueError("{...
Returns: The value to assign to the variable. Note: Subclasses will implement the abstract method :meth:`_get_value_to_set`, which should return a new value to set, or return None to do nothing.
def get_value_to_set(self): """ Returns: The value to assign to the variable. Note: Subclasses will implement the abstract method :meth:`_get_value_to_set`, which should return a new value to set, or return None to do nothing. """ ...
Using schedule, compute the value to be set at a given point.
def _get_value_to_set_at_point(self, point): """ Using schedule, compute the value to be set at a given point. """ laste, lastv = None, None for e, v in self.schedule: if e == point: return v # meet the exact boundary, return directly if...
This function should build the model which takes the input variables and return cost at the end
def build_graph(self, image, label): """This function should build the model which takes the input variables and return cost at the end""" # In tensorflow, inputs to convolution function are assumed to be # NHWC. Add a single channel here. image = tf.expand_dims(image, 3) ...
Convert a caffe parameter name to a tensorflow parameter name as defined in the above model
def name_conversion(caffe_layer_name): """ Convert a caffe parameter name to a tensorflow parameter name as defined in the above model """ # beginning & end mapping NAME_MAP = {'bn_conv1/beta': 'conv0/bn/beta', 'bn_conv1/gamma': 'conv0/bn/gamma', 'bn_conv1/mean/EMA': ...
Args: custom_getter: the same as in :func:`tf.get_variable` Returns: The current variable scope with a custom_getter.
def custom_getter_scope(custom_getter): """ Args: custom_getter: the same as in :func:`tf.get_variable` Returns: The current variable scope with a custom_getter. """ scope = tf.get_variable_scope() if get_tf_version_tuple() >= (1, 5): with tf.variable_scope( ...
Use fn to map the output of any variable getter. Args: fn (tf.Variable -> tf.Tensor) Returns: The current variable scope with a custom_getter that maps all the variables by fn. Example: .. code-block:: python with varreplace.remap_variables(lambda var: quantiz...
def remap_variables(fn): """ Use fn to map the output of any variable getter. Args: fn (tf.Variable -> tf.Tensor) Returns: The current variable scope with a custom_getter that maps all the variables by fn. Example: .. code-block:: python with varreplac...
Return a context to freeze variables, by wrapping ``tf.get_variable`` with a custom getter. It works by either applying ``tf.stop_gradient`` on the variables, or by keeping them out of the ``TRAINABLE_VARIABLES`` collection, or both. Example: .. code-block:: python with varrepl...
def freeze_variables(stop_gradient=True, skip_collection=False): """ Return a context to freeze variables, by wrapping ``tf.get_variable`` with a custom getter. It works by either applying ``tf.stop_gradient`` on the variables, or by keeping them out of the ``TRAINABLE_VARIABLES`` collection, or ...
Load a caffe model. You must be able to ``import caffe`` to use this function. Args: model_desc (str): path to caffe model description file (.prototxt). model_file (str): path to caffe model parameter file (.caffemodel). Returns: dict: the parameters.
def load_caffe(model_desc, model_file): """ Load a caffe model. You must be able to ``import caffe`` to use this function. Args: model_desc (str): path to caffe model description file (.prototxt). model_file (str): path to caffe model parameter file (.caffemodel). Returns: di...
Get caffe protobuf. Returns: The imported caffe protobuf module.
def get_caffe_pb(): """ Get caffe protobuf. Returns: The imported caffe protobuf module. """ dir = get_dataset_path('caffe') caffe_pb_file = os.path.join(dir, 'caffe_pb2.py') if not os.path.isfile(caffe_pb_file): download(CAFFE_PROTO_URL, dir) assert os.path.isfile(os...
Run some sanity checks, and populate some configs from others
def finalize_configs(is_training): """ Run some sanity checks, and populate some configs from others """ _C.freeze(False) # populate new keys now _C.DATA.NUM_CLASS = _C.DATA.NUM_CATEGORY + 1 # +1 background _C.DATA.BASEDIR = os.path.expanduser(_C.DATA.BASEDIR) if isinstance(_C.DATA.VAL, si...
Convert to a nested dict.
def to_dict(self): """Convert to a nested dict. """ return {k: v.to_dict() if isinstance(v, AttrDict) else v for k, v in self.__dict__.items() if not k.startswith('_')}
Update from command line args.
def update_args(self, args): """Update from command line args. """ for cfg in args: keys, v = cfg.split('=', maxsplit=1) keylist = keys.split('.') dic = self for i, k in enumerate(keylist[:-1]): assert k in dir(dic), "Unknown config key: {...
Get a corresponding model loader by looking at the file name. Returns: SessInit: either a :class:`DictRestore` (if name ends with 'npy/npz') or :class:`SaverRestore` (otherwise).
def get_model_loader(filename): """ Get a corresponding model loader by looking at the file name. Returns: SessInit: either a :class:`DictRestore` (if name ends with 'npy/npz') or :class:`SaverRestore` (otherwise). """ assert isinstance(filename, six.string_types), filename file...
return a set of strings
def _read_checkpoint_vars(model_path): """ return a set of strings """ reader = tf.train.NewCheckpointReader(model_path) reader = CheckpointReaderAdapter(reader) # use an adapter to standardize the name ckpt_vars = reader.get_variable_to_shape_map().keys() return reader, set(c...
Args: layers (list or layer): layer or list of layers to apply the arguments. Returns: a context where all appearance of these layer will by default have the arguments specified by kwargs. Example: .. code-block:: python with argscope(Conv2D, kernel_shape=3, nl=tf....
def argscope(layers, **kwargs): """ Args: layers (list or layer): layer or list of layers to apply the arguments. Returns: a context where all appearance of these layer will by default have the arguments specified by kwargs. Example: .. code-block:: python ...
Decorator for function to support argscope Example: .. code-block:: python from mylib import myfunc myfunc = enable_argscope_for_function(myfunc) Args: func: A function mapping one or multiple tensors to one or multiple tensors. log_shape (bool): S...
def enable_argscope_for_function(func, log_shape=True): """Decorator for function to support argscope Example: .. code-block:: python from mylib import myfunc myfunc = enable_argscope_for_function(myfunc) Args: func: A function mapping one or multiple tensors to o...
Overwrite all functions of a given module to support argscope. Note that this function monkey-patches the module and therefore could have unexpected consequences. It has been only tested to work well with ``tf.layers`` module. Example: .. code-block:: python import tensorflow as t...
def enable_argscope_for_module(module, log_shape=True): """ Overwrite all functions of a given module to support argscope. Note that this function monkey-patches the module and therefore could have unexpected consequences. It has been only tested to work well with ``tf.layers`` module. Example:...
Generate tensor for TensorBoard (casting, clipping) Args: name: name for visualization operation *imgs: multiple tensors as list scale_func: scale input tensors to fit range [0, 255] Example: visualize_tensors('viz1', [img1]) visualize_tensors('viz2', [img1, img2, img3]...
def visualize_tensors(name, imgs, scale_func=lambda x: (x + 1.) * 128., max_outputs=1): """Generate tensor for TensorBoard (casting, clipping) Args: name: name for visualization operation *imgs: multiple tensors as list scale_func: scale input tensors to fit range [0, 255] Example:...
img: an RGB image of shape (s, 2s, 3). :return: [input, output]
def split_input(img): """ img: an RGB image of shape (s, 2s, 3). :return: [input, output] """ # split the image into left + right pairs s = img.shape[0] assert img.shape[1] == 2 * s input, output = img[:, :s, :], img[:, s:, :] if args.mode == 'BtoA': input, output = output, i...
return a (b, 1) logits
def discriminator(self, inputs, outputs): """ return a (b, 1) logits""" l = tf.concat([inputs, outputs], 3) with argscope(Conv2D, kernel_size=4, strides=2, activation=BNLReLU): l = (LinearWrap(l) .Conv2D('conv0', NF, activation=tf.nn.leaky_relu) .Con...
A simple print Op that might be easier to use than :meth:`tf.Print`. Use it like: ``x = print_stat(x, message='This is x')``.
def print_stat(x, message=None): """ A simple print Op that might be easier to use than :meth:`tf.Print`. Use it like: ``x = print_stat(x, message='This is x')``. """ if message is None: message = x.op.name lst = [tf.shape(x), tf.reduce_mean(x)] if x.dtype.is_floating: lst.ap...
Returns: root mean square of tensor x.
def rms(x, name=None): """ Returns: root mean square of tensor x. """ if name is None: name = x.op.name + '/rms' with tfv1.name_scope(None): # name already contains the scope return tf.sqrt(tf.reduce_mean(tf.square(x)), name=name) return tf.sqrt(tf.reduce_mean(t...
`Peek Signal to Noise Ratio <https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio>`_. .. math:: PSNR = 20 \cdot \log_{10}(MAX_p) - 10 \cdot \log_{10}(MSE) Args: prediction: a :class:`tf.Tensor` representing the prediction signal. ground_truth: another :class:`tf.Tensor` with the s...
def psnr(prediction, ground_truth, maxp=None, name='psnr'): """`Peek Signal to Noise Ratio <https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio>`_. .. math:: PSNR = 20 \cdot \log_{10}(MAX_p) - 10 \cdot \log_{10}(MSE) Args: prediction: a :class:`tf.Tensor` representing the prediction ...
Args: anchor: coordinate of the center
def get_gaussian_weight(self, anchor): """ Args: anchor: coordinate of the center """ ret = np.zeros(self.shape, dtype='float32') y, x = np.mgrid[:self.shape[0], :self.shape[1]] y = y.astype('float32') / ret.shape[0] - anchor[0] x = x.astype('float32'...
Pad tensor in H, W Remarks: TensorFlow uses "ceil(input_spatial_shape[i] / strides[i])" rather than explicit padding like Caffe, pyTorch does. Hence, we need to pad here beforehand. Args: x (tf.tensor): incoming tensor p (int, optional): padding for H, W Returns: t...
def pad(x, p=3): """Pad tensor in H, W Remarks: TensorFlow uses "ceil(input_spatial_shape[i] / strides[i])" rather than explicit padding like Caffe, pyTorch does. Hence, we need to pad here beforehand. Args: x (tf.tensor): incoming tensor p (int, optional): padding for H, W...
Correlation Cost Volume computation. This is a fallback Python-only implementation, specialized just for FlowNet2. It takes a lot of memory and is slow. If you know to compile a custom op yourself, it's better to use the cuda implementation here: https://github.com/PatWie/tensorflow-recipes/tree/maste...
def correlation(ina, inb, kernel_size, max_displacement, stride_1, stride_2, pad, data_format): """ Correlation Cost Volume computation. This is a fallback Python-only implementation, specialized just for FlowNet2. It takes a lot of memory and is slow. ...
Resize input tensor with unkown input-shape by a factor Args: x (tf.Tensor): tensor NCHW factor (int, optional): resize factor for H, W Note: Differences here against Caffe have huge impacts on the quality of the predictions. Returns: tf.Tensor: resized tensor NCHW
def resize(x, mode, factor=4): """Resize input tensor with unkown input-shape by a factor Args: x (tf.Tensor): tensor NCHW factor (int, optional): resize factor for H, W Note: Differences here against Caffe have huge impacts on the quality of the predictions. Returns: ...
Architecture in Table 4 of FlowNet 2.0. Args: x: NCHW tensor, where C=11 is the concatenation of 7 items of [3, 2, 2, 1, 1, 1, 1] channels.
def flownet2_fusion(self, x): """ Architecture in Table 4 of FlowNet 2.0. Args: x: NCHW tensor, where C=11 is the concatenation of 7 items of [3, 2, 2, 1, 1, 1, 1] channels. """ with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1), ...
Architecture in Table 3 of FlowNet 2.0. Args: x: concatenation of two inputs, of shape [1, 2xC, H, W]
def flownet2_sd(self, x): """ Architecture in Table 3 of FlowNet 2.0. Args: x: concatenation of two inputs, of shape [1, 2xC, H, W] """ with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1), padding='valid', strides=2, ...
Architecture of FlowNetSimple in Figure 2 of FlowNet 1.0. Args: x: 2CHW if standalone==True, else NCHW where C=12 is a concatenation of 5 tensors of [3, 3, 3, 2, 1] channels. standalone: If True, this model is used to predict flow from two inputs. If Fals...
def graph_structure(self, x, standalone=True): """ Architecture of FlowNetSimple in Figure 2 of FlowNet 1.0. Args: x: 2CHW if standalone==True, else NCHW where C=12 is a concatenation of 5 tensors of [3, 3, 3, 2, 1] channels. standalone: If True, this mod...
Architecture of FlowNetCorr in Figure 2 of FlowNet 1.0. Args: x: 2CHW.
def graph_structure(self, x1x2): """ Architecture of FlowNetCorr in Figure 2 of FlowNet 1.0. Args: x: 2CHW. """ with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1), padding='valid', strides=2, kernel_size=3, ...
Will not modify img
def draw_annotation(img, boxes, klass, is_crowd=None): """Will not modify img""" labels = [] assert len(boxes) == len(klass) if is_crowd is not None: assert len(boxes) == len(is_crowd) for cls, crd in zip(klass, is_crowd): clsname = cfg.DATA.CLASS_NAMES[cls] if cr...
Draw top3 proposals for each gt. Args: proposals: NPx4 proposal_scores: NP gt_boxes: NG
def draw_proposal_recall(img, proposals, proposal_scores, gt_boxes): """ Draw top3 proposals for each gt. Args: proposals: NPx4 proposal_scores: NP gt_boxes: NG """ box_ious = np_iou(gt_boxes, proposals) # ng x np box_ious_argsort = np.argsort(-box_ious, axis=1) go...
Args: boxes: kx4 scores: kxC
def draw_predictions(img, boxes, scores): """ Args: boxes: kx4 scores: kxC """ if len(boxes) == 0: return img labels = scores.argmax(axis=1) scores = scores.max(axis=1) tags = ["{},{:.2f}".format(cfg.DATA.CLASS_NAMES[lb], score) for lb, score in zip(labels, scores)] ...
Args: results: [DetectionResult]
def draw_final_outputs(img, results): """ Args: results: [DetectionResult] """ if len(results) == 0: return img # Display in largest to smallest order to reduce occlusion boxes = np.asarray([r.box for r in results]) areas = np_area(boxes) sorted_inds = np.argsort(-areas)...
Overlay a mask on top of the image. Args: im: a 3-channel uint8 image in BGR mask: a binary 1-channel image of the same size color: if None, will choose automatically
def draw_mask(im, mask, alpha=0.5, color=None): """ Overlay a mask on top of the image. Args: im: a 3-channel uint8 image in BGR mask: a binary 1-channel image of the same size color: if None, will choose automatically """ if color is None: color = PALETTE_RGB[np.ran...
Run DataFlow and send data to a ZMQ socket addr. It will serialize and send each datapoint to this address with a PUSH socket. This function never returns. Args: df (DataFlow): Will infinitely loop over the DataFlow. addr: a ZMQ socket endpoint. hwm (int): ZMQ high-water mark (buffe...
def send_dataflow_zmq(df, addr, hwm=50, format=None, bind=False): """ Run DataFlow and send data to a ZMQ socket addr. It will serialize and send each datapoint to this address with a PUSH socket. This function never returns. Args: df (DataFlow): Will infinitely loop over the DataFlow. ...
Convert a DataFlow to a :class:`multiprocessing.Queue`. The DataFlow will only be reset in the spawned process. Args: df (DataFlow): the DataFlow to dump. size (int): size of the queue nr_consumer (int): number of consumer of the queue. The producer will add this many of ``D...
def dump_dataflow_to_process_queue(df, size, nr_consumer): """ Convert a DataFlow to a :class:`multiprocessing.Queue`. The DataFlow will only be reset in the spawned process. Args: df (DataFlow): the DataFlow to dump. size (int): size of the queue nr_consumer (int): number of co...
:returns: the current 3-channel image
def _grab_raw_image(self): """ :returns: the current 3-channel image """ m = self.ale.getScreenRGB() return m.reshape((self.height, self.width, 3))
:returns: a gray-scale (h, w) uint8 image
def _current_state(self): """ :returns: a gray-scale (h, w) uint8 image """ ret = self._grab_raw_image() # max-pooled over the last screen ret = np.maximum(ret, self.last_raw_screen) if self.viz: if isinstance(self.viz, float): cv2.imsh...
Args: boxes: nx4, xyxy window: [h, w]
def clip_boxes(boxes, window, name=None): """ Args: boxes: nx4, xyxy window: [h, w] """ boxes = tf.maximum(boxes, 0.0) m = tf.tile(tf.reverse(window, [0]), [2]) # (4,) boxes = tf.minimum(boxes, tf.cast(m, tf.float32), name=name) return boxes
Args: box_predictions: (..., 4), logits anchors: (..., 4), floatbox. Must have the same shape Returns: box_decoded: (..., 4), float32. With the same shape.
def decode_bbox_target(box_predictions, anchors): """ Args: box_predictions: (..., 4), logits anchors: (..., 4), floatbox. Must have the same shape Returns: box_decoded: (..., 4), float32. With the same shape. """ orig_shape = tf.shape(anchors) box_pred_txtytwth = tf.res...
Args: boxes: (..., 4), float32 anchors: (..., 4), float32 Returns: box_encoded: (..., 4), float32 with the same shape.
def encode_bbox_target(boxes, anchors): """ Args: boxes: (..., 4), float32 anchors: (..., 4), float32 Returns: box_encoded: (..., 4), float32 with the same shape. """ anchors_x1y1x2y2 = tf.reshape(anchors, (-1, 2, 2)) anchors_x1y1, anchors_x2y2 = tf.split(anchors_x1y1x2y...
Aligned version of tf.image.crop_and_resize, following our definition of floating point boxes. Args: image: NCHW boxes: nx4, x1y1x2y2 box_ind: (n,) crop_size (int): Returns: n,C,size,size
def crop_and_resize(image, boxes, box_ind, crop_size, pad_border=True): """ Aligned version of tf.image.crop_and_resize, following our definition of floating point boxes. Args: image: NCHW boxes: nx4, x1y1x2y2 box_ind: (n,) crop_size (int): Returns: n,C,size,size...
Args: featuremap: 1xCxHxW boxes: Nx4 floatbox resolution: output spatial resolution Returns: NxCx res x res
def roi_align(featuremap, boxes, resolution): """ Args: featuremap: 1xCxHxW boxes: Nx4 floatbox resolution: output spatial resolution Returns: NxCx res x res """ # sample 4 locations per roi bin ret = crop_and_resize( featuremap, boxes, tf.zeros([...
Slice anchors to the spatial size of this featuremap.
def narrow_to(self, featuremap): """ Slice anchors to the spatial size of this featuremap. """ shape2d = tf.shape(featuremap)[2:] # h,w slice3d = tf.concat([shape2d, [-1]], axis=0) slice4d = tf.concat([shape2d, [-1, -1]], axis=0) boxes = tf.slice(self.boxes, [0, ...
img: bgr, [0,255] heatmap: [0,1]
def colorize(img, heatmap): """ img: bgr, [0,255] heatmap: [0,1] """ heatmap = viz.intensity_to_rgb(heatmap, cmap='jet')[:, :, ::-1] return img * 0.5 + heatmap * 0.5
The correct center is shape*0.5-0.5. This can be verified by: SHAPE = 7 arr = np.random.rand(SHAPE, SHAPE) orig = arr c = SHAPE * 0.5 - 0.5 c = (c, c) for k in range(4): mat = cv2.getRotationMatrix2D(c, 90, 1) arr = cv2.warpAffine(arr, mat, arr.sh...
def _get_augment_params(self, img): center = img.shape[1::-1] * self._rand_range( self.center_range[0], self.center_range[1], (2,)) deg = self._rand_range(-self.max_deg, self.max_deg) if self.step_deg: deg = deg // self.step_deg * self.step_deg """ The cor...
Get largest rectangle after rotation. http://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders
def largest_rotated_rect(w, h, angle): """ Get largest rectangle after rotation. http://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders """ angle = angle / 180.0 * math.pi if w <= 0 or h <= 0: return 0, 0 width_is_longer =...
Apply a mapping on certain argument before calling the original function. Args: maps (dict): {argument_name: map_func}
def map_arg(**maps): """ Apply a mapping on certain argument before calling the original function. Args: maps (dict): {argument_name: map_func} """ def deco(func): @functools.wraps(func) def wrapper(*args, **kwargs): if six.PY2: argmap = inspect.g...
Like memoized, but keep one cache per default graph.
def graph_memoized(func): """ Like memoized, but keep one cache per default graph. """ # TODO it keeps the graph alive from ..compat import tfv1 GRAPH_ARG_NAME = '__IMPOSSIBLE_NAME_FOR_YOU__' @memoized def func_with_graph_arg(*args, **kwargs): kwargs.pop(GRAPH_ARG_NAME) ...
A decorator. It performs memoization ignoring the arguments used to call the function.
def memoized_ignoreargs(func): """ A decorator. It performs memoization ignoring the arguments used to call the function. """ def wrapper(*args, **kwargs): if func not in _MEMOIZED_NOARGS: res = func(*args, **kwargs) _MEMOIZED_NOARGS[func] = res return res...
Ensure a 2D shape. Args: a: a int or tuple/list of length 2 Returns: list: of length 2. if ``a`` is a int, return ``[a, a]``.
def shape2d(a): """ Ensure a 2D shape. Args: a: a int or tuple/list of length 2 Returns: list: of length 2. if ``a`` is a int, return ``[a, a]``. """ if type(a) == int: return [a, a] if isinstance(a, (list, tuple)): assert len(a) == 2 return list(a) ...
Ensuer a 4D shape, to use with 4D symbolic functions. Args: a: a int or tuple/list of length 2 Returns: list: of length 4. if ``a`` is a int, return ``[1, a, a, 1]`` or ``[1, 1, a, a]`` depending on data_format.
def shape4d(a, data_format='NHWC'): """ Ensuer a 4D shape, to use with 4D symbolic functions. Args: a: a int or tuple/list of length 2 Returns: list: of length 4. if ``a`` is a int, return ``[1, a, a, 1]`` or ``[1, 1, a, a]`` depending on data_format. """ s2d = shap...