Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def num_devices(self): c_count = c_uint() _check_return(_NVML.get_function( "nvmlDeviceGetCount_v2")(byref(c_count))) return c_count.value
[ "Get number of devices " ]
Please provide a description of the function:def device(self, idx): class GpuDevice(Structure): pass c_nvmlDevice_t = POINTER(GpuDevice) c_index = c_uint(idx) device = c_nvmlDevice_t() _check_return(_NVML.get_function( "nvmlDeviceGetHandleByInd...
[ "Get a specific GPU device\n\n Args:\n idx: index of device\n\n Returns:\n NvidiaDevice: single GPU device\n " ]
Please provide a description of the function:def maybe_download_and_extract(dest_directory, cifar_classnum): assert cifar_classnum == 10 or cifar_classnum == 100 if cifar_classnum == 10: cifar_foldername = 'cifar-10-batches-py' else: cifar_foldername = 'cifar-100-python' if os.path....
[ "Download and extract the tarball from Alex's website. Copied from tensorflow example " ]
Please provide a description of the function:def get_per_pixel_mean(self, names=('train', 'test')): for name in names: assert name in ['train', 'test'], name train_files, test_files, _ = get_filenames(self.dir, self.cifar_classnum) all_files = [] if 'train' in names:...
[ "\n Args:\n names (tuple[str]): the names ('train' or 'test') of the datasets\n\n Returns:\n a mean image of all images in the given datasets, with size 32x32x3\n " ]
Please provide a description of the function:def get_per_channel_mean(self, names=('train', 'test')): mean = self.get_per_pixel_mean(names) return np.mean(mean, axis=(0, 1))
[ "\n Args:\n names (tuple[str]): the names ('train' or 'test') of the datasets\n\n Returns:\n An array of three values as mean of each channel, for all images in the given datasets.\n " ]
Please provide a description of the function:def maskrcnn_loss(mask_logits, fg_labels, fg_target_masks): num_fg = tf.size(fg_labels, out_type=tf.int64) indices = tf.stack([tf.range(num_fg), fg_labels - 1], axis=1) # #fgx2 mask_logits = tf.gather_nd(mask_logits, indices) # #fgxhxw mask_probs = tf....
[ "\n Args:\n mask_logits: #fg x #category xhxw\n fg_labels: #fg, in 1~#class, int64\n fg_target_masks: #fgxhxw, float32\n " ]
Please provide a description of the function:def maskrcnn_upXconv_head(feature, num_category, num_convs, norm=None): assert norm in [None, 'GN'], norm l = feature with argscope([Conv2D, Conv2DTranspose], data_format='channels_first', kernel_initializer=tf.variance_scaling_initializer(...
[ "\n Args:\n feature (NxCx s x s): size is 7 in C4 models and 14 in FPN models.\n num_category(int):\n num_convs (int): number of convolution layers\n norm (str or None): either None or 'GN'\n\n Returns:\n mask_logits (N x num_category x 2s x 2s):\n " ]
Please provide a description of the function:def get_per_pixel_mean(names=('train', 'test', 'extra')): for name in names: assert name in ['train', 'test', 'extra'], name images = [SVHNDigit(x).X for x in names] return np.concatenate(tuple(images)).mean(axis=0)
[ "\n Args:\n names (tuple[str]): names of the dataset split\n\n Returns:\n a 32x32x3 image, the mean of all images in the given datasets\n " ]
Please provide a description of the function:def build_or_reuse_placeholder(tensor_spec): g = tfv1.get_default_graph() name = tensor_spec.name try: tensor = g.get_tensor_by_name(name + ':0') assert "Placeholder" in tensor.op.type, "Tensor {} exists but is not a placeholder!".format(name...
[ "\n Build a tf.placeholder from the metadata in the given tensor spec, or return an existing one.\n\n Args:\n tensor_spec (tf.TensorSpec):\n\n Returns:\n tf.Tensor:\n " ]
Please provide a description of the function:def get_input_signature(self): with tf.Graph().as_default() as G: # create these placeholder in a temporary graph inputs = self.inputs() if isinstance(inputs[0], tf.Tensor): for p in inputs: asser...
[ "\n Returns:\n A list of :class:`tf.TensorSpec`, which describes the inputs of this model.\n The result is cached for each instance of :class:`ModelDescBase`.\n " ]
Please provide a description of the function:def dependency_of_targets(targets, op): # TODO tensorarray? sparsetensor? if isinstance(op, tf.Tensor): op = op.op assert isinstance(op, tf.Operation), op from tensorflow.contrib.graph_editor import get_backward_walk_ops # alternative implem...
[ "\n Check that op is in the subgraph induced by the dependencies of targets.\n The result is memoized.\n\n This is useful if some SessionRunHooks should be run only together with certain ops.\n\n Args:\n targets: a tuple of ops or tensors. The targets to find dependencies of.\n op (tf.Oper...
Please provide a description of the function:def dependency_of_fetches(fetches, op): try: from tensorflow.python.client.session import _FetchHandler as FetchHandler # use the graph of the op, so that this function can be called without being under a default graph handler = FetchHandler(...
[ "\n Check that op is in the subgraph induced by the dependencies of fetches.\n fetches may have more general structure.\n\n Args:\n fetches: An argument to `sess.run`. Nested structure will affect performance.\n op (tf.Operation or tf.Tensor):\n\n Returns:\n bool: True if any of `fe...
Please provide a description of the function:def create_scalar_summary(name, v): assert isinstance(name, six.string_types), type(name) v = float(v) s = tf.Summary() s.value.add(tag=name, simple_value=v) return s
[ "\n Args:\n name (str):\n v (float): scalar value\n Returns:\n tf.Summary: a tf.Summary object with name and simple scalar value v.\n " ]
Please provide a description of the function:def create_image_summary(name, val): assert isinstance(name, six.string_types), type(name) n, h, w, c = val.shape val = val.astype('uint8') s = tf.Summary() imparams = [cv2.IMWRITE_PNG_COMPRESSION, 9] for k in range(n): arr = val[k] ...
[ "\n Args:\n name(str):\n val(np.ndarray): 4D tensor of NHWC. assume RGB if C==3.\n Can be either float or uint8. Range has to be [0,255].\n\n Returns:\n tf.Summary:\n " ]
Please provide a description of the function:def add_tensor_summary(x, types, name=None, collections=None, main_tower_only=True): types = set(types) if name is None: name = x.op.name ctx = get_current_tower_context() if main_tower_only and ctx is not None and not ctx....
[ "\n Summarize a tensor by different methods.\n\n Args:\n x (tf.Tensor): a tensor to summarize\n types (list[str]): summary types, can be scalar/histogram/sparsity/mean/rms\n name (str): summary name. Defaults to be the op name.\n collections (list[str]): collections of the summary ...
Please provide a description of the function:def add_activation_summary(x, types=None, name=None, collections=None): ndim = x.get_shape().ndims if ndim < 2: logger.warn("Cannot summarize scalar activation {}".format(x.name)) return if types is None: types = ['sparsity', 'rms', '...
[ "\n Call :func:`add_tensor_summary` under a reused 'activation-summary' name scope.\n This function is a no-op if not calling from main training tower.\n\n Args:\n x (tf.Tensor): the tensor to summary.\n types (list[str]): summary types, defaults to ``['sparsity', 'rms', 'histogram']``.\n ...
Please provide a description of the function:def add_param_summary(*summary_lists, **kwargs): collections = kwargs.pop('collections', None) assert len(kwargs) == 0, "Unknown kwargs: " + str(kwargs) ctx = get_current_tower_context() if ctx is not None and not ctx.is_main_training_tower: retu...
[ "\n Add summary ops for all trainable variables matching the regex, under a\n reused 'param-summary' name scope.\n This function is a no-op if not calling from main training tower.\n\n Args:\n summary_lists (list): each is (regex, [list of summary type]).\n Summary type is defined in :...
Please provide a description of the function:def add_moving_summary(*args, **kwargs): decay = kwargs.pop('decay', 0.95) coll = kwargs.pop('collection', MOVING_SUMMARY_OPS_KEY) summ_coll = kwargs.pop('summary_collections', None) assert len(kwargs) == 0, "Unknown arguments: " + str(kwargs) ctx =...
[ "\n Summarize the moving average for scalar tensors.\n This function is a no-op if not calling from main training tower.\n\n Args:\n args: scalar tensors to summarize\n decay (float): the decay rate. Defaults to 0.95.\n collection (str or None): the name of the collection to add EMA-ma...
Please provide a description of the function:def run_head(self, proposals, stage): reg_weights = tf.constant(cfg.CASCADE.BBOX_REG_WEIGHTS[stage], dtype=tf.float32) pooled_feature = self.roi_func(proposals.boxes) # N,C,S,S pooled_feature = self.scale_gradient(pooled_feature) hea...
[ "\n Args:\n proposals: BoxProposals\n stage: 0, 1, 2\n\n Returns:\n FastRCNNHead\n Nx4, updated boxes\n " ]
Please provide a description of the function:def match_box_with_gt(self, boxes, iou_threshold): if self.is_training: with tf.name_scope('match_box_with_gt_{}'.format(iou_threshold)): iou = pairwise_iou(boxes, self.gt_boxes) # NxM max_iou_per_box = tf.reduce_...
[ "\n Args:\n boxes: Nx4\n Returns:\n BoxProposals\n " ]
Please provide a description of the function:def decoded_output_boxes(self): ret = self._cascade_boxes[-1] ret = tf.expand_dims(ret, 1) # class-agnostic return tf.tile(ret, [1, self.num_classes, 1])
[ "\n Returns:\n Nx#classx4\n " ]
Please provide a description of the function:def output_scores(self, name=None): scores = [head.output_scores('cascade_scores_stage{}'.format(idx + 1)) for idx, head in enumerate(self._heads)] return tf.multiply(tf.add_n(scores), (1.0 / self.num_cascade_stages), name=name)
[ "\n Returns:\n Nx#class\n " ]
Please provide a description of the function:def do_visualize(model, model_path, nr_visualize=100, output_dir='output'): df = get_train_dataflow() # we don't visualize mask stuff df.reset_state() pred = OfflinePredictor(PredictConfig( model=model, session_init=get_model_loader(model_...
[ "\n Visualize some intermediate results (proposals, raw predictions) inside the pipeline.\n " ]
Please provide a description of the function:def get_registered_layer(name): ret = _LAYER_REGISTRY.get(name, None) if ret == _NameConflict: raise KeyError("Layer named '{}' is registered with `@layer_register` more than once!".format(name)) return ret
[ "\n Args:\n name (str): the name of the layer, e.g. 'Conv2D'\n Returns:\n the wrapped layer function, or None if not registered.\n " ]
Please provide a description of the function:def layer_register( log_shape=False, use_scope=True): def wrapper(func): @wraps(func) def wrapped_func(*args, **kwargs): assert args[0] is not None, args if use_scope: name, inputs = args[0], a...
[ "\n Args:\n log_shape (bool): log input/output shape of this layer\n use_scope (bool or None):\n Whether to call this layer with an extra first argument as variable scope.\n When set to None, it can be called either with or without\n the scope name argument, depend ...
Please provide a description of the function:def get_predictor(self, input_names, output_names, device=0): assert self.tower_func is not None, "Must set tower_func on the trainer to use get_predictor()!" tower_name = 'tower-pred-{}'.format(device) if device >= 0 else 'tower-pred-cpu' de...
[ "\n This method will build the trainer's tower function under ``TowerContext(is_training=False)``,\n and returns a callable predictor with input placeholders & output tensors in this tower.\n\n This method handles the common case of inference with the same tower function.\n If you want t...
Please provide a description of the function:def export_serving(model_path): pred_config = PredictConfig( session_init=get_model_loader(model_path), model=InferenceOnlyModel(), input_names=['input_img_bytes'], output_names=['prediction_img_bytes']) ModelExporter(pred_config)...
[ "Export trained model to use it in TensorFlow Serving or cloudML. " ]
Please provide a description of the function:def export_compact(model_path): pred_config = PredictConfig( session_init=get_model_loader(model_path), model=Model(), input_names=['input_img'], output_names=['prediction_img']) ModelExporter(pred_config).export_compact('/tmp/com...
[ "Export trained model to use it as a frozen and pruned inference graph in\n mobile applications. " ]
Please provide a description of the function:def apply(model_path): pred_config = PredictConfig( session_init=get_model_loader(model_path), model=Model(), input_names=['input_img'], output_names=['prediction_img']) pred = OfflinePredictor(pred_config) img = cv2.imread('...
[ "Run inference from a training model checkpoint. " ]
Please provide a description of the function:def apply_inference_graph(model_path): pred_config = PredictConfig( session_init=get_model_loader(model_path), model=InferenceOnlyModel(), input_names=['input_img_bytes'], output_names=['prediction_img_bytes']) pred = OfflinePred...
[ "Run inference from a different graph, which receives encoded images buffers. " ]
Please provide a description of the function:def apply_compact(graph_path): with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess: # Note, we just load the graph and do *not* need to initialize anything. with tf.gfile.GFile(graph_path, "rb") as f: graph_def = tf....
[ "Run the pruned and frozen inference graph. " ]
Please provide a description of the function:def BatchNorm(inputs, training=None, momentum=0.9, epsilon=1e-5, center=True, scale=True, gamma_initializer=tf.ones_initializer(), data_format='channels_last', internal_update=False): data_format = get_data_for...
[ "\n Mostly equivalent to `tf.layers.batch_normalization`, but difference in\n the following:\n 1. Accepts `data_format` rather than `axis`. For 2D input, this argument will be ignored.\n 2. Default value for `momentum` and `epsilon` is different.\n 3. Default value for `training` is automatically obt...
Please provide a description of the function:def SelectComponent(ds, idxs): return MapData(ds, lambda dp: [dp[i] for i in idxs])
[ "\n Select / reorder components from datapoints.\n\n Args:\n ds (DataFlow): input DataFlow.\n idxs (list[int]): a list of component indices.\n\n Example:\n\n .. code-block:: none\n\n original df produces: [c1, c2, c3]\n idxs: [2,1]\n this df: [c3, c2]\n " ]
Please provide a description of the function:def _analyze_input_data(self, entry, k, depth=1, max_depth=3, max_list=3): class _elementInfo(object): def __init__(self, el, pos, depth=0, max_list=3): self.shape = "" self.type = type(el).__name__ ...
[ "\n Gather useful debug information from a datapoint.\n\n Args:\n entry: the datapoint component\n k (int): index of this component in current datapoint\n depth (int, optional): recursion depth\n max_depth, max_list: same as in :meth:`__init__`.\n\n R...
Please provide a description of the function:def feed(self, count, total=1): self._tot += total self._cnt += count
[ "\n Args:\n cnt(int): the count of some event of interest.\n tot(int): the total number of events.\n " ]
Please provide a description of the function:def feed(self, pred, label): assert pred.shape == label.shape, "{} != {}".format(pred.shape, label.shape) self.nr_pos += (label == 1).sum() self.nr_neg += (label == 0).sum() self.nr_pred_pos += (pred == 1).sum() self.nr_pred_n...
[ "\n Args:\n pred (np.ndarray): binary array.\n label (np.ndarray): binary array of the same size.\n " ]
Please provide a description of the function:def apply_grad_processors(opt, gradprocs): assert isinstance(gradprocs, (list, tuple)), gradprocs for gp in gradprocs: assert isinstance(gp, GradientProcessor), gp class _ApplyGradientProcessor(ProxyOptimizer): def __init__(self, opt, gradpr...
[ "\n Wrapper around optimizers to apply gradient processors.\n\n Args:\n opt (tf.train.Optimizer):\n gradprocs (list[GradientProcessor]): gradient processors to add to the\n optimizer.\n\n Returns:\n a :class:`tf.train.Optimizer` instance which runs the gradient\n proc...
Please provide a description of the function:def _paste_mask(box, mask, shape): # int() is floor # box fpcoor=0.0 -> intcoor=0.0 x0, y0 = list(map(int, box[:2] + 0.5)) # box fpcoor=h -> intcoor=h-1, inclusive x1, y1 = list(map(int, box[2:] - 0.5)) # inclusive x1 = max(x0, x1) # requir...
[ "\n Args:\n box: 4 float\n mask: MxM floats\n shape: h,w\n Returns:\n A uint8 binary image of hxw.\n " ]
Please provide a description of the function:def predict_image(img, model_func): orig_shape = img.shape[:2] resizer = CustomResize(cfg.PREPROC.TEST_SHORT_EDGE_SIZE, cfg.PREPROC.MAX_SIZE) resized_img = resizer.augment(img) scale = np.sqrt(resized_img.shape[0] * 1.0 / img.shape[0] * resized_img.shap...
[ "\n Run detection on one image, using the TF callable.\n This function should handle the preprocessing internally.\n\n Args:\n img: an image\n model_func: a callable from the TF model.\n It takes image and returns (boxes, probs, labels, [masks])\n\n Returns:\n [DetectionR...
Please provide a description of the function:def predict_dataflow(df, model_func, tqdm_bar=None): df.reset_state() all_results = [] with ExitStack() as stack: # tqdm is not quite thread-safe: https://github.com/tqdm/tqdm/issues/323 if tqdm_bar is None: tqdm_bar = stack.enter...
[ "\n Args:\n df: a DataFlow which produces (image, image_id)\n model_func: a callable from the TF model.\n It takes image and returns (boxes, probs, labels, [masks])\n tqdm_bar: a tqdm object to be shared among multiple evaluation instances. If None,\n will create a new ...
Please provide a description of the function:def multithread_predict_dataflow(dataflows, model_funcs): num_worker = len(model_funcs) assert len(dataflows) == num_worker if num_worker == 1: return predict_dataflow(dataflows[0], model_funcs[0]) kwargs = {'thread_name_prefix': 'EvalWorker'} if...
[ "\n Running multiple `predict_dataflow` in multiple threads, and aggregate the results.\n\n Args:\n dataflows: a list of DataFlow to be used in :func:`predict_dataflow`\n model_funcs: a list of callable to be used in :func:`predict_dataflow`\n\n Returns:\n list of dict, in the format u...
Please provide a description of the function:def batch_flatten(x): shape = x.get_shape().as_list()[1:] if None not in shape: return tf.reshape(x, [-1, int(np.prod(shape))]) return tf.reshape(x, tf.stack([tf.shape(x)[0], -1]))
[ "\n Flatten the tensor except the first dimension.\n " ]
Please provide a description of the function:def FullyConnected( inputs, units, activation=None, use_bias=True, kernel_initializer=None, bias_initializer=tf.zeros_initializer(), kernel_regularizer=None, bias_regularizer=None, activity_regularizer=N...
[ "\n A wrapper around `tf.layers.Dense`.\n One difference to maintain backward-compatibility:\n Default weight initializer is variance_scaling_initializer(2.0).\n\n Variable Names:\n\n * ``W``: weights of shape [in_dim, out_dim]\n * ``b``: bias\n " ]
Please provide a description of the function:def _init_runtime(self): if self.idx != 0: from tensorpack.models.registry import disable_layer_logging disable_layer_logging() self.predictor = OfflinePredictor(self.config) if self.idx == 0: with self.pre...
[ " Call _init_runtime under different CUDA_VISIBLE_DEVICES, you'll\n have workers that run on multiGPUs\n " ]
Please provide a description of the function:def fetch_batch(self): inp, f = self.queue.get() nr_input_var = len(inp) batched, futures = [[] for _ in range(nr_input_var)], [] for k in range(nr_input_var): batched[k].append(inp[k]) futures.append(f) wh...
[ " Fetch a batch of data without waiting" ]
Please provide a description of the function:def put_task(self, dp, callback=None): f = Future() if callback is not None: f.add_done_callback(callback) self.input_queue.put((dp, f)) return f
[ "\n Same as in :meth:`AsyncPredictorBase.put_task`.\n " ]
Please provide a description of the function:def loads_msgpack(buf): # Since 0.6, the default max size was set to 1MB. # We change it to approximately 1G. return msgpack.loads(buf, raw=False, max_bin_len=MAX_MSGPACK_LEN, max_array_len=MAX_MSGPACK_LEN, ...
[ "\n Args:\n buf: the output of `dumps`.\n " ]
Please provide a description of the function:def BatchNorm(inputs, axis=None, training=None, momentum=0.9, epsilon=1e-5, center=True, scale=True, beta_initializer=tf.zeros_initializer(), gamma_initializer=tf.ones_initializer(), virtual_batch_size=None, ...
[ "\n Almost equivalent to `tf.layers.batch_normalization`, but different (and more powerful)\n in the following:\n\n 1. Accepts an alternative `data_format` option when `axis` is None. For 2D input, this argument will be ignored.\n 2. Default value for `momentum` and `epsilon` is different.\n 3. Defau...
Please provide a description of the function:def BatchRenorm(x, rmax, dmax, momentum=0.9, epsilon=1e-5, center=True, scale=True, gamma_initializer=None, data_format='channels_last'): shape = x.get_shape().as_list() ndims = len(shape) assert ndims in [2, 4] if ndims ...
[ "\n Batch Renormalization layer, as described in the paper:\n `Batch Renormalization: Towards Reducing Minibatch Dependence in Batch-Normalized Models\n <https://arxiv.org/abs/1702.03275>`_.\n This implementation is a wrapper around `tf.layers.batch_normalization`.\n\n Args:\n x (tf.Tensor): a...
Please provide a description of the function:def generator(self, z): nf = 64 l = FullyConnected('fc0', z, nf * 8 * 4 * 4, activation=tf.identity) l = tf.reshape(l, [-1, 4, 4, nf * 8]) l = BNReLU(l) with argscope(Conv2DTranspose, activation=BNReLU, kernel_size=4, strides=...
[ " return an image generated from z" ]
Please provide a description of the function:def discriminator(self, imgs): nf = 64 with argscope(Conv2D, kernel_size=4, strides=2): l = (LinearWrap(imgs) .Conv2D('conv0', nf, activation=tf.nn.leaky_relu) .Conv2D('conv1', nf * 2) .B...
[ " return a (b, 1) logits" ]
Please provide a description of the function:def area(boxes): x_min, y_min, x_max, y_max = tf.split(boxes, 4, axis=1) return tf.squeeze((y_max - y_min) * (x_max - x_min), [1])
[ "\n Args:\n boxes: nx4 floatbox\n\n Returns:\n n\n " ]
Please provide a description of the function:def pairwise_intersection(boxlist1, boxlist2): x_min1, y_min1, x_max1, y_max1 = tf.split(boxlist1, 4, axis=1) x_min2, y_min2, x_max2, y_max2 = tf.split(boxlist2, 4, axis=1) all_pairs_min_ymax = tf.minimum(y_max1, tf.transpose(y_max2)) all_pairs_max_ymin ...
[ "Compute pairwise intersection areas between boxes.\n\n Args:\n boxlist1: Nx4 floatbox\n boxlist2: Mx4\n\n Returns:\n a tensor with shape [N, M] representing pairwise intersections\n " ]
Please provide a description of the function:def pairwise_iou(boxlist1, boxlist2): intersections = pairwise_intersection(boxlist1, boxlist2) areas1 = area(boxlist1) areas2 = area(boxlist2) unions = ( tf.expand_dims(areas1, 1) + tf.expand_dims(areas2, 0) - intersections) return tf.where(...
[ "Computes pairwise intersection-over-union between box collections.\n\n Args:\n boxlist1: Nx4 floatbox\n boxlist2: Mx4\n\n Returns:\n a tensor with shape [N, M] representing pairwise iou scores.\n " ]
Please provide a description of the function:def sample(path, start, length): # initialize vocabulary and sequence length param.seq_len = 1 ds = CharRNNData(param.corpus, 100000) pred = OfflinePredictor(PredictConfig( model=Model(), session_init=SaverRestore(path), input_na...
[ "\n :param path: path to the model\n :param start: a `str`. the starting characters\n :param length: a `int`. the length of text to generate\n " ]
Please provide a description of the function:def Maxout(x, num_unit): input_shape = x.get_shape().as_list() ndim = len(input_shape) assert ndim == 4 or ndim == 2 ch = input_shape[-1] assert ch is not None and ch % num_unit == 0 if ndim == 4: x = tf.reshape(x, [-1, input_shape[1], in...
[ "\n Maxout as in the paper `Maxout Networks <http://arxiv.org/abs/1302.4389>`_.\n\n Args:\n x (tf.Tensor): a NHWC or NC tensor. Channel has to be known.\n num_unit (int): a int. Must be divisible by C.\n\n Returns:\n tf.Tensor: of shape NHW(C/num_unit) named ``output``.\n " ]
Please provide a description of the function:def PReLU(x, init=0.001, name='output'): init = tfv1.constant_initializer(init) alpha = tfv1.get_variable('alpha', [], initializer=init) x = ((1 + alpha) * x + (1 - alpha) * tf.abs(x)) ret = tf.multiply(x, 0.5, name=name) ret.variables = VariableHol...
[ "\n Parameterized ReLU as in the paper `Delving Deep into Rectifiers: Surpassing\n Human-Level Performance on ImageNet Classification\n <http://arxiv.org/abs/1502.01852>`_.\n\n Args:\n x (tf.Tensor): input\n init (float): initial value for the learnable slope.\n name (str): name of ...
Please provide a description of the function:def BNReLU(x, name=None): x = BatchNorm('bn', x) x = tf.nn.relu(x, name=name) return x
[ "\n A shorthand of BatchNormalization + ReLU.\n " ]
Please provide a description of the function:def GroupNorm(x, group=32, gamma_initializer=tf.constant_initializer(1.)): shape = x.get_shape().as_list() ndims = len(shape) assert ndims == 4, shape chan = shape[1] assert chan % group == 0, chan group_size = chan // group orig_shape = tf....
[ "\n More code that reproduces the paper can be found at https://github.com/ppwwyyxx/GroupNorm-reproduce/.\n " ]
Please provide a description of the function:def backbone_scope(freeze): def nonlin(x): x = get_norm()(x) return tf.nn.relu(x) with argscope([Conv2D, MaxPooling, BatchNorm], data_format='channels_first'), \ argscope(Conv2D, use_bias=False, activation=nonlin, ...
[ "\n Args:\n freeze (bool): whether to freeze all the variables under the scope\n " ]
Please provide a description of the function:def extract_images(filename): with gzip.open(filename) as bytestream: magic = _read32(bytestream) if magic != 2051: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % (magic, filename)) ...
[ "Extract the images into a 4D uint8 numpy array [index, y, x, depth]." ]
Please provide a description of the function:def extract_labels(filename): with gzip.open(filename) as bytestream: magic = _read32(bytestream) if magic != 2049: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (magic, filename)) ...
[ "Extract the labels into a 1D uint8 numpy array [index]." ]
Please provide a description of the function:def create_dummy_class(klass, dependency): assert not building_rtfd() class _DummyMetaClass(type): # throw error on class attribute access def __getattr__(_, __): raise AttributeError("Cannot import '{}', therefore '{}' is not availa...
[ "\n When a dependency of a class is not available, create a dummy class which throws ImportError when used.\n\n Args:\n klass (str): name of the class.\n dependency (str): name of the dependency.\n\n Returns:\n class: a class object\n " ]
Please provide a description of the function:def create_dummy_func(func, dependency): assert not building_rtfd() if isinstance(dependency, (list, tuple)): dependency = ','.join(dependency) def _dummy(*args, **kwargs): raise ImportError("Cannot import '{}', therefore '{}' is not availa...
[ "\n When a dependency of a function is not available, create a dummy function which throws ImportError when used.\n\n Args:\n func (str): name of the function.\n dependency (str or list[str]): name(s) of the dependency.\n\n Returns:\n function: a function object\n " ]
Please provide a description of the function:def log_deprecated(name="", text="", eos=""): assert name or text if eos: eos = "after " + datetime(*map(int, eos.split("-"))).strftime("%d %b") if name: if eos: warn_msg = "%s will be deprecated %s. %s" % (name, eos, text) ...
[ "\n Log deprecation warning.\n\n Args:\n name (str): name of the deprecated item.\n text (str, optional): information about the deprecation.\n eos (str, optional): end of service date such as \"YYYY-MM-DD\".\n " ]
Please provide a description of the function:def deprecated(text="", eos=""): def get_location(): import inspect frame = inspect.currentframe() if frame: callstack = inspect.getouterframes(frame)[-1] return '%s:%i' % (callstack[1], callstack[2]) else: ...
[ "\n Args:\n text, eos: same as :func:`log_deprecated`.\n\n Returns:\n a decorator which deprecates the function.\n\n Example:\n .. code-block:: python\n\n @deprecated(\"Explanation of what to do instead.\", \"2017-11-4\")\n def foo(...):\n pass\n ...
Please provide a description of the function:def refill_queue(self): self.thread.pause() # pause enqueue opt = tfv1.RunOptions() opt.timeout_in_ms = 2000 # 2s sess = tfv1.get_default_session() # dequeue until empty try: while True: ...
[ "\n Clear the queue, then call dataflow.__iter__() again and fill into the queue.\n " ]
Please provide a description of the function:def _create_ema_callback(self): with self.cached_name_scope(): # in TF there is no API to get queue capacity, so we can only summary the size size = tf.cast(self.queue.size(), tf.float32, name='queue_size') size_ema_op = add_m...
[ "\n Create a hook-only callback which maintain EMA of the queue size.\n Also tf.summary.scalar the EMA.\n " ]
Please provide a description of the function:def _setup(self, inputs): logger.info("Setting up the queue for CPU prefetching ...") self.input_placehdrs = [build_or_reuse_placeholder(v) for v in inputs] assert len(self.input_placehdrs) > 0, \ "BatchQueueInput has to be used with some ...
[]
Please provide a description of the function:def dataflow_to_dataset(df, types): # TODO theoretically it can support dict assert isinstance(df, DataFlow), df assert isinstance(types, (list, tuple)), types df = MapData(df, lambda dp: tuple(dp)) df.reset_state() ds...
[ "\n Wrap a dataflow to tf.data.Dataset.\n This function will also reset the dataflow.\n\n If the dataflow itself is finite, the returned dataset is also finite.\n Therefore, if used for training, you'll need to add `.repeat()` on the returned\n dataset.\n\n Args:\n ...
Please provide a description of the function:def get_predictor(self, n): l = len(self.predictors) if n >= l: logger.warn("n > #towers, will assign predictor to GPU by round-robin") return [self.predictors[k % l] for k in range(n)]
[ "\n Returns:\n OnlinePredictor: the nth predictor on the nth tower.\n " ]
Please provide a description of the function:def intersection(boxes1, boxes2): [y_min1, x_min1, y_max1, x_max1] = np.split(boxes1, 4, axis=1) [y_min2, x_min2, y_max2, x_max2] = np.split(boxes2, 4, axis=1) all_pairs_min_ymax = np.minimum(y_max1, np.transpose(y_max2)) all_pairs_max_ymin = np.maximum(y_min1, n...
[ "Compute pairwise intersection areas between boxes.\n\n Args:\n boxes1: a numpy array with shape [N, 4] holding N boxes\n boxes2: a numpy array with shape [M, 4] holding M boxes\n\n Returns:\n a numpy array with shape [N*M] representing pairwise intersection area\n " ]
Please provide a description of the function:def iou(boxes1, boxes2): intersect = intersection(boxes1, boxes2) area1 = area(boxes1) area2 = area(boxes2) union = np.expand_dims(area1, axis=1) + np.expand_dims( area2, axis=0) - intersect return intersect / union
[ "Computes pairwise intersection-over-union between box collections.\n\n Args:\n boxes1: a numpy array with shape [N, 4] holding N boxes.\n boxes2: a numpy array with shape [M, 4] holding M boxes.\n\n Returns:\n a numpy array with shape [N, M] representing pairwise iou scores.\n " ]
Please provide a description of the function:def ioa(boxes1, boxes2): intersect = intersection(boxes1, boxes2) inv_areas = np.expand_dims(1.0 / area(boxes2), axis=0) return intersect * inv_areas
[ "Computes pairwise intersection-over-area between box collections.\n\n Intersection-over-area (ioa) between two boxes box1 and box2 is defined as\n their intersection area over box2's area. Note that ioa is not symmetric,\n that is, IOA(box1, box2) != IOA(box2, box1).\n\n Args:\n boxes1: a numpy array with s...
Please provide a description of the function:def maybe_download(url, work_directory): filename = url.split("/")[-1] filepath = os.path.join(work_directory, filename) if not os.path.exists(filepath): logger.info("Downloading to {}...".format(filepath)) download(url, work_directory) r...
[ "Download the data from Marlin's website, unless it's already here." ]
Please provide a description of the function:def get_synset_1000(self): fname = os.path.join(self.dir, 'synsets.txt') assert os.path.isfile(fname) lines = [x.strip() for x in open(fname).readlines()] return dict(enumerate(lines))
[ "\n Returns:\n dict: {cls_number: synset_id}\n " ]
Please provide a description of the function:def get_image_list(self, name, dir_structure='original'): assert name in ['train', 'val', 'test'] assert dir_structure in ['original', 'train'] add_label_to_fname = (name != 'train' and dir_structure != 'original') if add_label_to_fna...
[ "\n Args:\n name (str): 'train' or 'val' or 'test'\n dir_structure (str): same as in :meth:`ILSVRC12.__init__()`.\n Returns:\n list: list of (image filename, label)\n " ]
Please provide a description of the function:def get_per_pixel_mean(self, size=None): if self.caffepb is None: self.caffepb = get_caffe_pb() obj = self.caffepb.BlobProto() mean_file = os.path.join(self.dir, 'imagenet_mean.binaryproto') with open(mean_file, 'rb') as ...
[ "\n Args:\n size (tuple): image size in (h, w). Defaults to (256, 256).\n Returns:\n np.ndarray: per-pixel mean of shape (h, w, 3 (BGR)) in range [0, 255].\n " ]
Please provide a description of the function:def guess_dir_structure(dir): subdir = os.listdir(dir)[0] # find a subdir starting with 'n' if subdir.startswith('n') and \ os.path.isdir(os.path.join(dir, subdir)): dir_structure = 'train' else: ...
[ "\n Return the directory structure of \"dir\".\n\n Args:\n dir(str): something like '/path/to/imagenet/val'\n\n Returns:\n either 'train' or 'original'\n " ]
Please provide a description of the function:def print_coco_metrics(self, json_file): from pycocotools.cocoeval import COCOeval ret = {} cocoDt = self.coco.loadRes(json_file) cocoEval = COCOeval(self.coco, cocoDt, 'bbox') cocoEval.evaluate() cocoEval.accumulate()...
[ "\n Args:\n json_file (str): path to the results json file in coco format\n Returns:\n dict: the evaluation metrics\n " ]
Please provide a description of the function:def load(self, add_gt=True, add_mask=False): if add_mask: assert add_gt with timed_operation('Load Groundtruth Boxes for {}'.format(self.name)): img_ids = self.coco.getImgIds() img_ids.sort() # list of ...
[ "\n Args:\n add_gt: whether to add ground truth bounding box annotations to the dicts\n add_mask: whether to also add ground truth mask\n\n Returns:\n a list of dict, each has keys including:\n 'image_id', 'file_name',\n and (if add_gt is ...
Please provide a description of the function:def _use_absolute_file_name(self, img): img['file_name'] = os.path.join( self._imgdir, img['file_name']) assert os.path.isfile(img['file_name']), img['file_name']
[ "\n Change relative filename to abosolute file name.\n " ]
Please provide a description of the function:def _add_detection_gt(self, img, add_mask): # ann_ids = self.coco.getAnnIds(imgIds=img['image_id']) # objs = self.coco.loadAnns(ann_ids) objs = self.coco.imgToAnns[img['image_id']] # equivalent but faster than the above two lines # ...
[ "\n Add 'boxes', 'class', 'is_crowd' of this image to the dict, used by detection.\n If add_mask is True, also add 'segmentation' in coco poly format.\n " ]
Please provide a description of the function:def load_many(basedir, names, add_gt=True, add_mask=False): if not isinstance(names, (list, tuple)): names = [names] ret = [] for n in names: coco = COCODetection(basedir, n) ret.extend(coco.load(add_gt, ad...
[ "\n Load and merges several instance files together.\n\n Returns the same format as :meth:`COCODetection.load`.\n " ]
Please provide a description of the function:def load_training_roidbs(self, names): return COCODetection.load_many( cfg.DATA.BASEDIR, names, add_gt=True, add_mask=cfg.MODE_MASK)
[ "\n Args:\n names (list[str]): name of the training datasets, e.g. ['train2014', 'valminusminival2014']\n\n Returns:\n roidbs (list[dict]):\n\n Produce \"roidbs\" as a list of dict, each dict corresponds to one image with k>=0 instances.\n and the following keys ar...
Please provide a description of the function:def load_inference_roidbs(self, name): return COCODetection.load_many(cfg.DATA.BASEDIR, name, add_gt=False)
[ "\n Args:\n name (str): name of one inference dataset, e.g. 'minival2014'\n\n Returns:\n roidbs (list[dict]):\n\n Each dict corresponds to one image to run inference on. The\n following keys in the dict are expected:\n\n file_name (str): full path...
Please provide a description of the function:def eval_or_save_inference_results(self, results, dataset, output=None): continuous_id_to_COCO_id = {v: k for k, v in COCODetection.COCO_id_to_category_id.items()} for res in results: # convert to COCO's incontinuous category id ...
[ "\n Args:\n results (list[dict]): the inference results as dicts.\n Each dict corresponds to one __instance__. It contains the following keys:\n\n image_id (str): the id that matches `load_inference_roidbs`.\n category_id (int): the category prediction,...
Please provide a description of the function:def timed_operation(msg, log_start=False): assert len(msg) if log_start: logger.info('Start {} ...'.format(msg)) start = timer() yield msg = msg[0].upper() + msg[1:] logger.info('{} finished, time:{:.4f} sec.'.format( msg, timer()...
[ "\n Surround a context with a timer.\n\n Args:\n msg(str): the log to print.\n log_start(bool): whether to print also at the beginning.\n\n Example:\n .. code-block:: python\n\n with timed_operation('Good Stuff'):\n time.sleep(1)\n\n Will print:\n\n ...
Please provide a description of the function:def total_timer(msg): start = timer() yield t = timer() - start _TOTAL_TIMER_DATA[msg].feed(t)
[ " A context which add the time spent inside to TotalTimer. " ]
Please provide a description of the function:def print_total_timer(): if len(_TOTAL_TIMER_DATA) == 0: return for k, v in six.iteritems(_TOTAL_TIMER_DATA): logger.info("Total Time: {} -> {:.2f} sec, {} times, {:.3g} sec/time".format( k, v.sum, v.count, v.average))
[ "\n Print the content of the TotalTimer, if it's not empty. This function will automatically get\n called when program exits.\n " ]
Please provide a description of the function:def reset_state(self): super(AugmentorList, self).reset_state() for a in self.augmentors: a.reset_state()
[ " Will reset state of each augmentor " ]
Please provide a description of the function:def ensure_proc_terminate(proc): if isinstance(proc, list): for p in proc: ensure_proc_terminate(p) return def stop_proc_by_weak_ref(ref): proc = ref() if proc is None: return if not proc.is_alive(...
[ "\n Make sure processes terminate when main process exit.\n\n Args:\n proc (multiprocessing.Process or list)\n " ]
Please provide a description of the function:def enable_death_signal(_warn=True): if platform.system() != 'Linux': return try: import prctl # pip install python-prctl except ImportError: if _warn: log_once('"import prctl" failed! Install python-prctl so that proce...
[ "\n Set the \"death signal\" of the current process, so that\n the current process will be cleaned with guarantee\n in case the parent dies accidentally.\n " ]
Please provide a description of the function:def mask_sigint(): if is_main_thread(): sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN) yield True signal.signal(signal.SIGINT, sigint_handler) else: yield False
[ "\n Returns:\n If called in main thread, returns a context where ``SIGINT`` is ignored, and yield True.\n Otherwise yield False.\n " ]
Please provide a description of the function:def start_proc_mask_signal(proc): if not isinstance(proc, list): proc = [proc] with mask_sigint(): for p in proc: if isinstance(p, mp.Process): if sys.version_info < (3, 4) or mp.get_start_method() == 'fork': ...
[ "\n Start process(es) with SIGINT ignored.\n\n Args:\n proc: (mp.Process or list)\n\n Note:\n The signal mask is only applied when called from main thread.\n " ]
Please provide a description of the function:def subproc_call(cmd, timeout=None): try: output = subprocess.check_output( cmd, stderr=subprocess.STDOUT, shell=True, timeout=timeout) return output, 0 except subprocess.TimeoutExpired as e: logger.warn("Command '...
[ "\n Execute a command with timeout, and return STDOUT and STDERR\n\n Args:\n cmd(str): the command to execute.\n timeout(float): timeout in seconds.\n\n Returns:\n output(bytes), retcode(int). If timeout, retcode is -1.\n " ]
Please provide a description of the function:def queue_put_stoppable(self, q, obj): while not self.stopped(): try: q.put(obj, timeout=5) break except queue.Full: pass
[ " Put obj to queue, but will give up when the thread is stopped" ]
Please provide a description of the function:def queue_get_stoppable(self, q): while not self.stopped(): try: return q.get(timeout=5) except queue.Empty: pass
[ " Take obj from queue, but will give up when the thread is stopped" ]
Please provide a description of the function:def put(self, rank, val): idx = bisect.bisect(self.ranks, rank) self.ranks.insert(idx, rank) self.data.insert(idx, val)
[ "\n Args:\n rank(int): rank of th element. All elements must have different ranks.\n val: an object\n " ]
Please provide a description of the function:def visualize_conv_weights(filters, name): with tf.name_scope('visualize_w_' + name): filters = tf.transpose(filters, (3, 2, 0, 1)) # [h, w, cin, cout] -> [cout, cin, h, w] filters = tf.unstack(filters) # --> cout * [cin, h, w] ...
[ "Visualize use weights in convolution filters.\n\n Args:\n filters: tensor containing the weights [H,W,Cin,Cout]\n name: label for tensorboard\n\n Returns:\n image of all weight\n " ]