INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns: mean max: two stats of the runners to be added to backend
def reset_stats(self): """ Returns: mean, max: two stats of the runners, to be added to backend """ scores = list(itertools.chain.from_iterable([v.total_scores for v in self._runners])) for v in self._runners: v.total_scores.clear() try: ...
log the time of some heavy callbacks
def log(self): """ log the time of some heavy callbacks """ 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( "Callbacks...
The context for a tower function containing metadata about the current tower. Tensorpack trainers use: class: TowerContext to manage tower function. Many tensorpack layers have to be called under a: class: TowerContext.
def TowerContext(tower_name, is_training, vs_name=''): """ The context for a tower function, containing metadata about the current tower. Tensorpack trainers use :class:`TowerContext` to manage tower function. Many tensorpack layers have to be called under a :class:`TowerContext`. Example: .. ...
Returns: A: class: TowerTensorHandles containing only the training towers.
def training(self): """ Returns: A :class:`TowerTensorHandles`, containing only the training towers. """ handles = [h for h in self._handles if h.is_training] return TowerTensorHandles(handles)
Returns: A: class: TowerTensorHandles containing only the inference towers.
def inference(self): """ Returns: A :class:`TowerTensorHandles`, containing only the inference towers. """ handles = [h for h in self._handles if not h.is_training] return TowerTensorHandles(handles)
Get a tensor in this tower. The name can be:
def get_tensor(self, name): """ Get a tensor in this tower. The name can be: 1. The name of the tensor without any tower prefix. 2. A name in the input signature, if it is used when building the tower. In the second case, this method will return the tensor that's used as the c...
Get a variable used in this tower. The name should not contain the variable scope prefix of the tower.
def get_variable(self, name): """ Get a variable used in this tower. The name should not contain the variable scope prefix of the tower. When the tower has the same variable scope and name scope, this is equivalent to :meth:`get_tensor`. """ name = get_op_tensor_...
See: meth: BaseTowerContext. get_collection_in_tower.
def get_collection(self, key=None, name=None): """ See :meth:`BaseTowerContext.get_collection_in_tower`. Args: key (str): the key of the collection name: deprecated """ if name is not None: logger.warn("TowerTensorHandle.get_collection(name=.....
Like mkdir - p make a dir recursively but do nothing if the dir exists
def mkdir_p(dirname): """ Like "mkdir -p", make a dir recursively, but do nothing if the dir exists Args: dirname(str): """ assert dirname is not None if dirname == '' or os.path.isdir(dirname): return try: os.makedirs(dirname) except OSError as e: if e.errno...
Download URL to a directory. Will figure out the filename automatically from URL if not given.
def download(url, dir, filename=None, expect_size=None): """ Download URL to a directory. Will figure out the filename automatically from URL, if not given. """ mkdir_p(dir) if filename is None: filename = url.split('/')[-1] fpath = os.path.join(dir, filename) if os.path.isfile(...
Yields: str: All files in rootdir recursively.
def recursive_walk(rootdir): """ Yields: str: All files in rootdir, recursively. """ for r, dirs, files in os.walk(rootdir): for f in files: yield os.path.join(r, f)
Get the path to some dataset under $TENSORPACK_DATASET.
def get_dataset_path(*args): """ Get the path to some dataset under ``$TENSORPACK_DATASET``. Args: args: strings to be joined to form path. Returns: str: path to the dataset. """ d = os.environ.get('TENSORPACK_DATASET', None) if d is None: d = os.path.join(os.path.e...
Args: keys ( list ): list of collection keys to backup. Defaults to all keys in the graph.
def backup_collection(keys=None): """ Args: keys (list): list of collection keys to backup. Defaults to all keys in the graph. Returns: dict: the backup """ if keys is None: keys = tf.get_default_graph().get_all_collection_keys() ret = {} assert isinstanc...
Restore from a collection backup.
def restore_collection(backup): """ Restore from a collection backup. Args: backup (dict): """ for k, v in six.iteritems(backup): del tf.get_collection_ref(k)[:] tf.get_collection_ref(k).extend(v)
Get items from this collection that are added in the current tower.
def get_collection_in_tower(self, key): """ Get items from this collection that are added in the current tower. """ 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]
Iterate on the raw PTB data.
def ptb_producer(raw_data, batch_size, num_steps, name=None): """Iterate on the raw PTB data. This chunks up raw_data into batches of examples and returns Tensors that are drawn from these batches. Args: raw_data: one of the raw data outputs from ptb_raw_data. batch_size: int, the batch size. num_...
Set the directory for global logging.
def set_logger_dir(dirname, action=None): """ Set the directory for global logging. Args: dirname(str): log directory action(str): an action of ["k","d","q"] to be performed when the directory exists. Will ask user by default. "d": delete the directory. Note tha...
Use: func: logger. set_logger_dir to set log directory to./ train_log/ { scriptname }: { name }. scriptname is the name of the main python file currently running
def auto_set_dir(action=None, name=None): """ Use :func:`logger.set_logger_dir` to set log directory to "./train_log/{scriptname}:{name}". "scriptname" is the name of the main python file currently running""" mod = sys.modules['__main__'] basename = os.path.basename(mod.__file__) auto_dirname = ...
The class - balanced cross entropy loss as in Holistically - Nested Edge Detection <http:// arxiv. org/ abs/ 1504. 06375 > _.
def class_balanced_sigmoid_cross_entropy(logits, label, name='cross_entropy_loss'): """ The class-balanced cross entropy loss, as in `Holistically-Nested Edge Detection <http://arxiv.org/abs/1504.06375>`_. Args: logits: of shape (b, ...). label: of the same shape. the ground truth i...
Deterministic bilinearly - upsample the input images. It is implemented by deconvolution with BilinearFiller in Caffe. It is aimed to mimic caffe behavior.
def CaffeBilinearUpSample(x, shape): """ Deterministic bilinearly-upsample the input images. It is implemented by deconvolution with "BilinearFiller" in Caffe. It is aimed to mimic caffe behavior. Args: x (tf.Tensor): a NCHW tensor shape (int): the upsample factor Returns: ...
All forked dataflows should only be reset ** once and only once ** in spawned processes. Subclasses should call this method with super.
def reset_state(self): """ All forked dataflows should only be reset **once and only once** in spawned processes. Subclasses should call this method with super. """ assert not self._reset_done, "reset_state() was called twice! This violates the API of DataFlow!" self._res...
Returns True if spec_or_tensor is compatible with this TensorSpec.
def is_compatible_with(self, spec_or_tensor): """Returns True if spec_or_tensor is compatible with this TensorSpec. Two tensors are considered compatible if they have the same dtype and their shapes are compatible (see `tf.TensorShape.is_compatible_with`). Args: spec_or_tensor: A tf.TensorSpec o...
Print a description of the current model parameters. Skip variables starting with tower as they are just duplicates built by data - parallel logic.
def describe_trainable_vars(): """ Print a description of the current model parameters. Skip variables starting with "tower", as they are just duplicates built by data-parallel logic. """ train_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) if len(train_vars) == 0: logger.war...
Internally used by layer registry to print shapes of inputs/ outputs of layers.
def get_shape_str(tensors): """ Internally used by layer registry, to print shapes of inputs/outputs of layers. Args: tensors (list or tf.Tensor): a tensor or a list of tensors Returns: str: a string to describe the shape """ if isinstance(tensors, (list, tuple)): for v ...
r Loss for Siamese networks as described in the paper: Learning a Similarity Metric Discriminatively with Application to Face Verification <http:// yann. lecun. com/ exdb/ publis/ pdf/ chopra - 05. pdf > _ by Chopra et al.
def contrastive_loss(left, right, y, margin, extra=False, scope="constrastive_loss"): r"""Loss for Siamese networks as described in the paper: `Learning a Similarity Metric Discriminatively, with Application to Face Verification <http://yann.lecun.com/exdb/publis/pdf/chopra-05.pdf>`_ by Chopra et al. ....
r Loss for Siamese networks ( cosine version ). Same as: func: contrastive_loss but with different similarity measurement.
def siamese_cosine_loss(left, right, y, scope="cosine_loss"): r"""Loss for Siamese networks (cosine version). Same as :func:`contrastive_loss` but with different similarity measurement. .. math:: [\frac{l \cdot r}{\lVert l\rVert \lVert r\rVert} - (2y-1)]^2 Args: left (tf.Tensor): left ...
r Loss for Triplet networks as described in the paper: FaceNet: A Unified Embedding for Face Recognition and Clustering <https:// arxiv. org/ abs/ 1503. 03832 > _ by Schroff et al.
def triplet_loss(anchor, positive, negative, margin, extra=False, scope="triplet_loss"): r"""Loss for Triplet networks as described in the paper: `FaceNet: A Unified Embedding for Face Recognition and Clustering <https://arxiv.org/abs/1503.03832>`_ by Schroff et al. Learn embeddings from an anchor ...
r Loss for triplet networks as described in the paper: Deep Metric Learning using Triplet Network <https:// arxiv. org/ abs/ 1412. 6622 > _ by Hoffer et al.
def soft_triplet_loss(anchor, positive, negative, extra=True, scope="soft_triplet_loss"): r"""Loss for triplet networks as described in the paper: `Deep Metric Learning using Triplet Network <https://arxiv.org/abs/1412.6622>`_ by Hoffer et al. It is a softmax loss using :math:`(anchor-positive)^2` and ...
r Center - Loss as described in the paper A Discriminative Feature Learning Approach for Deep Face Recognition <http:// ydwen. github. io/ papers/ WenECCV16. pdf > by Wen et al.
def center_loss(embedding, label, num_classes, alpha=0.1, scope="center_loss"): r"""Center-Loss as described in the paper `A Discriminative Feature Learning Approach for Deep Face Recognition` <http://ydwen.github.io/papers/WenECCV16.pdf> by Wen et al. Args: embedding (tf.Tensor): features prod...
Embed all given tensors into an nfeatures - dim space.
def embed(self, x, nfeatures=2): """Embed all given tensors into an nfeatures-dim space. """ list_split = 0 if isinstance(x, list): list_split = len(x) x = tf.concat(x, 0) # pre-process MNIST dataflow data x = tf.expand_dims(x, 3) x = x * 2 - 1 ...
Generate anchor ( reference ) windows by enumerating aspect ratios X scales wrt a reference ( 0 0 15 15 ) window.
def generate_anchors(base_size=16, ratios=[0.5, 1, 2], scales=2**np.arange(3, 6)): """ Generate anchor (reference) windows by enumerating aspect ratios X scales wrt a reference (0, 0, 15, 15) window. """ base_anchor = np.array([1, 1, base_size, base_size], dtype='float32') - 1 ...
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) ...
Args: roidbs ( list [ dict ] ): the same format as the output of load_training_roidbs.
def print_class_histogram(roidbs): """ Args: roidbs (list[dict]): the same format as the output of `load_training_roidbs`. """ dataset = DetectionDataset() hist_bins = np.arange(dataset.num_classes + 1) # Histogram of ground-truth objects gt_hist = np.zeros((dataset.num_classes,), d...
Get all anchors in the largest possible image shifted floatbox Args: stride ( int ): the stride of anchors. sizes ( tuple [ int ] ): the sizes ( sqrt area ) of anchors
def get_all_anchors(stride=None, sizes=None): """ Get all anchors in the largest possible image, shifted, floatbox Args: stride (int): the stride of anchors. sizes (tuple[int]): the sizes (sqrt area) of anchors Returns: anchors: SxSxNUM_ANCHORx4, where S == ceil(MAX_SIZE/STRIDE)...
Returns: [ anchors ]: each anchors is a SxSx NUM_ANCHOR_RATIOS x4 array.
def get_all_anchors_fpn(strides=None, sizes=None): """ Returns: [anchors]: each anchors is a SxSx NUM_ANCHOR_RATIOS x4 array. """ if strides is None: strides = cfg.FPN.ANCHOR_STRIDES if sizes is None: sizes = cfg.RPN.ANCHOR_SIZES assert len(strides) == len(sizes) foas...
Label each anchor as fg/ bg/ ignore. Args: anchors: Ax4 float gt_boxes: Bx4 float non - crowd crowd_boxes: Cx4 float
def get_anchor_labels(anchors, gt_boxes, crowd_boxes): """ Label each anchor as fg/bg/ignore. Args: anchors: Ax4 float gt_boxes: Bx4 float, non-crowd crowd_boxes: Cx4 float Returns: anchor_labels: (A,) int. Each element is {-1, 0, 1} anchor_boxes: Ax4. Contains t...
Args: im: an image boxes: nx4 floatbox gt. shoudn t be changed is_crowd: n
def get_rpn_anchor_input(im, boxes, is_crowd): """ Args: im: an image boxes: nx4, floatbox, gt. shoudn't be changed is_crowd: n, Returns: The anchor labels and target boxes for each pixel in the featuremap. fm_labels: fHxfWxNA fm_boxes: fHxfWxNAx4 NA ...
Args: im: an image boxes: nx4 floatbox gt. shoudn t be changed is_crowd: n
def get_multilevel_rpn_anchor_input(im, boxes, is_crowd): """ Args: im: an image boxes: nx4, floatbox, gt. shoudn't be changed is_crowd: n, Returns: [(fm_labels, fm_boxes)]: Returns a tuple for each FPN level. Each tuple contains the anchor labels and target boxes fo...
Return a training dataflow. Each datapoint consists of the following:
def get_train_dataflow(): """ Return a training dataflow. Each datapoint consists of the following: An image: (h, w, 3), 1 or more pairs of (anchor_labels, anchor_boxes): anchor_labels: (h', w', NA) anchor_boxes: (h', w', NA, 4) gt_boxes: (N, 4) gt_labels: (N,) If MODE_MASK, gt_m...
Args: name ( str ): name of the dataset to evaluate shard num_shards: to get subset of evaluation data
def get_eval_dataflow(name, shard=0, num_shards=1): """ Args: name (str): name of the dataset to evaluate shard, num_shards: to get subset of evaluation data """ roidbs = DetectionDataset().load_inference_roidbs(name) num_imgs = len(roidbs) img_per_shard = num_imgs // num_shards...
Returns: a context where all variables will be created as local.
def override_to_local_variable(enable=True): """ Returns: a context where all variables will be created as local. """ if enable: def custom_getter(getter, name, *args, **kwargs): _replace_global_by_local(kwargs) return getter(name, *args, **kwargs) with ...
Args: grad_list: K x N x 2
def split_grad_list(grad_list): """ Args: grad_list: K x N x 2 Returns: K x N: gradients K x N: variables """ g = [] v = [] for tower in grad_list: g.append([x[0] for x in tower]) v.append([x[1] for x in tower]) return g, v
Args: all_grads ( K x N ): gradients all_vars ( K x N ): variables
def merge_grad_list(all_grads, all_vars): """ Args: all_grads (K x N): gradients all_vars(K x N): variables Return: K x N x 2: list of list of (grad, var) pairs """ return [list(zip(gs, vs)) for gs, vs in zip(all_grads, all_vars)]
All - reduce average the gradients among K devices. Results are broadcasted to all devices.
def allreduce_grads(all_grads, average): """ All-reduce average the gradients among K devices. Results are broadcasted to all devices. Args: all_grads (K x N): List of list of gradients. N is the number of variables. average (bool): average gradients or not. Returns: K x N: sam...
Hierarchical allreduce for DGX - 1 system.
def allreduce_grads_hierarchical(all_grads, devices, average=False): """ Hierarchical allreduce for DGX-1 system. Args: all_grads (K x N): List of list of gradients. N is the number of variables. devices ([str]): K str for the K devices. average (bool): average gradients or not. ...
Average the gradients.
def aggregate_grads(all_grads, colocation=False, devices=None, average=True): """ Average the gradients. Args: all_grads (K x N x 2): A list of K lists. Each of the list is a list of N (grad, var) tuples. The variables have to ...
Returns: bool - False if grads cannot be packed due to various reasons.
def compute_strategy(self, grads): """ Returns: bool - False if grads cannot be packed due to various reasons. """ for g in grads: assert g.shape.is_fully_defined(), "Shape of {} is {}!".format(g.name, g.shape) self._shapes = [g.shape for g in grads] ...
Args: grads ( list ): list of gradient tensors
def pack(self, grads): """ Args: grads (list): list of gradient tensors Returns: packed list of gradient tensors to be aggregated. """ for i, g in enumerate(grads): assert g.shape == self._shapes[i] with cached_name_scope("GradientPac...
Args: all_grads: K x N K lists of gradients to be packed
def pack_all(self, all_grads, devices): """ Args: all_grads: K x N, K lists of gradients to be packed """ ret = [] # #GPU x #split for dev, grads in zip(devices, all_grads): with tf.device(dev): ret.append(self.pack(grads)) retur...
Args: all_packed: K lists of packed gradients.
def unpack_all(self, all_packed, devices): """ Args: all_packed: K lists of packed gradients. """ all_grads = [] # #GPU x #Var for dev, packed_grads_single_device in zip(devices, all_packed): with tf.device(dev): all_grads.append(self.unpa...
Args: features ( [ tf. Tensor ] ): ResNet features c2 - c5
def fpn_model(features): """ Args: features ([tf.Tensor]): ResNet features c2-c5 Returns: [tf.Tensor]: FPN features p2-p6 """ assert len(features) == 4, features num_channel = cfg.FPN.NUM_CHANNEL use_gn = cfg.FPN.NORM == 'GN' def upsample2x(name, x): return Fix...
Assign boxes to level 2~5.
def fpn_map_rois_to_levels(boxes): """ Assign boxes to level 2~5. Args: boxes (nx4): Returns: [tf.Tensor]: 4 tensors for level 2-5. Each tensor is a vector of indices of boxes in its level. [tf.Tensor]: 4 tensors, the gathered boxes in each level. Be careful that the retur...
Args: features ( [ tf. Tensor ] ): 4 FPN feature level 2 - 5 rcnn_boxes ( tf. Tensor ): nx4 boxes resolution ( int ): output spatial resolution Returns: NxC x res x res
def multilevel_roi_align(features, rcnn_boxes, resolution): """ Args: features ([tf.Tensor]): 4 FPN feature level 2-5 rcnn_boxes (tf.Tensor): nx4 boxes resolution (int): output spatial resolution Returns: NxC x res x res """ assert len(features) == 4, features # R...
Args: multilevel_anchors: #lvl RPNAnchors multilevel_label_logits: #lvl tensors of shape HxWxA multilevel_box_logits: #lvl tensors of shape HxWxAx4
def multilevel_rpn_losses( multilevel_anchors, multilevel_label_logits, multilevel_box_logits): """ Args: multilevel_anchors: #lvl RPNAnchors multilevel_label_logits: #lvl tensors of shape HxWxA multilevel_box_logits: #lvl tensors of shape HxWxAx4 Returns: label_loss...
Args: multilevel_pred_boxes: #lvl HxWxAx4 boxes multilevel_label_logits: #lvl tensors of shape HxWxA
def generate_fpn_proposals( multilevel_pred_boxes, multilevel_label_logits, image_shape2d): """ Args: multilevel_pred_boxes: #lvl HxWxAx4 boxes multilevel_label_logits: #lvl tensors of shape HxWxA Returns: boxes: kx4 float scores: k logits """ num_lvl = len(c...
Layer Normalization layer as described in the paper: Layer Normalization <https:// arxiv. org/ abs/ 1607. 06450 > _.
def LayerNorm( x, epsilon=1e-5, use_bias=True, use_scale=True, gamma_init=None, data_format='channels_last'): """ Layer Normalization layer, as described in the paper: `Layer Normalization <https://arxiv.org/abs/1607.06450>`_. Args: x (tf.Tensor): a 4D or 2D tensor. When...
Instance Normalization as in the paper: Instance Normalization: The Missing Ingredient for Fast Stylization <https:// arxiv. org/ abs/ 1607. 08022 > _.
def InstanceNorm(x, epsilon=1e-5, use_affine=True, gamma_init=None, data_format='channels_last'): """ Instance Normalization, as in the paper: `Instance Normalization: The Missing Ingredient for Fast Stylization <https://arxiv.org/abs/1607.08022>`_. Args: x (tf.Tensor): a 4D tensor. ...
Add summaries for RPN proposals.
def proposal_metrics(iou): """ Add summaries for RPN proposals. Args: iou: nxm, #proposal x #gt """ # find best roi for each gt, for summary only best_iou = tf.reduce_max(iou, axis=0) mean_best_iou = tf.reduce_mean(best_iou, name='best_iou_per_gt') summaries = [mean_best_iou] ...
Sample some boxes from all proposals for training. #fg is guaranteed to be > 0 because ground truth boxes will be added as proposals.
def sample_fast_rcnn_targets(boxes, gt_boxes, gt_labels): """ Sample some boxes from all proposals for training. #fg is guaranteed to be > 0, because ground truth boxes will be added as proposals. Args: boxes: nx4 region proposals, floatbox gt_boxes: mx4, floatbox gt_labels: m, ...
Args: feature ( any shape ): num_classes ( int ): num_category + 1 class_agnostic_regression ( bool ): if True regression to N x 1 x 4
def fastrcnn_outputs(feature, num_classes, class_agnostic_regression=False): """ Args: feature (any shape): num_classes(int): num_category + 1 class_agnostic_regression (bool): if True, regression to N x 1 x 4 Returns: cls_logits: N x num_class classification logits ...
Args: labels: n label_logits: nxC fg_boxes: nfgx4 encoded fg_box_logits: nfgxCx4 or nfgx1x4 if class agnostic
def fastrcnn_losses(labels, label_logits, fg_boxes, fg_box_logits): """ Args: labels: n, label_logits: nxC fg_boxes: nfgx4, encoded fg_box_logits: nfgxCx4 or nfgx1x4 if class agnostic Returns: label_loss, box_loss """ label_loss = tf.nn.sparse_softmax_cross_e...
Generate final results from predictions of all proposals.
def fastrcnn_predictions(boxes, scores): """ Generate final results from predictions of all proposals. Args: boxes: n#classx4 floatbox in float32 scores: nx#class Returns: boxes: Kx4 scores: K labels: K """ assert boxes.shape[1] == cfg.DATA.NUM_CLASS ...
Args: feature ( any shape ):
def fastrcnn_2fc_head(feature): """ Args: feature (any shape): Returns: 2D head feature """ dim = cfg.FPN.FRCNN_FC_HEAD_DIM init = tf.variance_scaling_initializer() hidden = FullyConnected('fc6', feature, dim, kernel_initializer=init, activation=tf.nn.relu) hidden = Full...
Args: feature ( NCHW ): num_classes ( int ): num_category + 1 num_convs ( int ): number of conv layers norm ( str or None ): either None or GN
def fastrcnn_Xconv1fc_head(feature, num_convs, norm=None): """ Args: feature (NCHW): num_classes(int): num_category + 1 num_convs (int): number of conv layers norm (str or None): either None or 'GN' Returns: 2D head feature """ assert norm in [None, 'GN'], no...
Returns: #fg x ? x 4
def fg_box_logits(self): """ Returns: #fg x ? x 4 """ return tf.gather(self.box_logits, self.proposals.fg_inds(), name='fg_box_logits')
Returns: N x #class x 4
def decoded_output_boxes(self): """ Returns: N x #class x 4 """ anchors = tf.tile(tf.expand_dims(self.proposals.boxes, 1), [1, cfg.DATA.NUM_CLASS, 1]) # N x #class x 4 decoded_boxes = decode_bbox_target( self.box_logits / self.bbox_regression_weights, ...
Returns: Nx4
def decoded_output_boxes_class_agnostic(self): """ Returns: Nx4 """ assert self._bbox_class_agnostic box_logits = tf.reshape(self.box_logits, [-1, 4]) decoded = decode_bbox_target( box_logits / self.bbox_regression_weights, self.proposals.boxes ) r...
Returns: N x #class scores summed to one for each box.
def output_scores(self, name=None): """ Returns: N x #class scores, summed to one for each box.""" return tf.nn.softmax(self.label_logits, name=name)
Launch forward prediction for the new state given by some client.
def _on_state(self, state, client): """ Launch forward prediction for the new state given by some client. """ def cb(outputs): try: distrib, value = outputs.result() except CancelledError: logger.info("Client {} cancelled.".format(c...
Process a message sent from some client.
def _process_msg(self, client, state, reward, isOver): """ Process a message sent from some client. """ # in the first message, only state is valid, # reward&isOver should be discarded if len(client.memory) > 0: client.memory[-1].reward = reward if...
return a ( b 1 ) logits
def discriminator(self, imgs, y): """ return a (b, 1) logits""" yv = y y = tf.reshape(y, [-1, 1, 1, 10]) with argscope(Conv2D, kernel_size=5, strides=1): l = (LinearWrap(imgs) .ConcatWith(tf.tile(y, [1, 28, 28, 1]), 3) .Conv2D('conv0', 11) ...
Create a self - contained inference - only graph and write final graph ( in pb format ) to disk.
def export_compact(self, filename, optimize=True, toco_compatible=False): """Create a self-contained inference-only graph and write final graph (in pb format) to disk. Args: filename (str): path to the output graph optimize (bool): whether to use TensorFlow's `optimize_for_infer...
Converts a checkpoint and graph to a servable for TensorFlow Serving. Use TF s SavedModelBuilder to export a trained model without tensorpack dependency.
def export_serving(self, filename, tags=[tf.saved_model.SERVING if is_tfv2() else tf.saved_model.tag_constants.SERVING], signature_name='prediction_pipeline'): """ Converts a checkpoint and graph to a servable for TensorFlow Serving. Use TF's `SavedM...
Use a Ray task to read a chunk of SQL source.
def _read_sql_with_offset_pandas_on_ray( partition_column, start, end, num_splits, sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=None, chunksize=None, ): # pragma: no cover """Use a Ray task to read a chunk of SQL source. No...
Read SQL query or database table into a DataFrame.
def read_sql( cls, sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=None, chunksize=None, partition_column=None, lower_bound=None, upper_bound=None, max_sessions=None, ): ...
Creates a decorator which overwrites a decorated class __doc__ attribute with parent s __doc__ attribute. Also overwrites __doc__ of methods and properties defined in the class with the __doc__ of matching methods and properties in parent.
def _inherit_docstrings(parent, excluded=[]): """Creates a decorator which overwrites a decorated class' __doc__ attribute with parent's __doc__ attribute. Also overwrites __doc__ of methods and properties defined in the class with the __doc__ of matching methods and properties in parent. Args: ...
This logs the time usage of a code block
def time_logger(name): """This logs the time usage of a code block""" start_time = time.time() yield end_time = time.time() total_time = end_time - start_time logging.info("%s; time: %ss", name, total_time)
Initializes ray based on environment variables and internal defaults.
def initialize_ray(): """Initializes ray based on environment variables and internal defaults.""" if threading.current_thread().name == "MainThread": plasma_directory = None object_store_memory = os.environ.get("MODIN_MEMORY", None) if os.environ.get("MODIN_OUT_OF_CORE", "False").title()...
Applies func to the object.
def apply( self, func, num_splits=None, other_axis_partition=None, maintain_partitioning=True, **kwargs ): """Applies func to the object. See notes in Parent class about this method. Args: func: The function to apply. ...
Convert categorical variable into indicator variables.
def get_dummies( data, prefix=None, prefix_sep="_", dummy_na=False, columns=None, sparse=False, drop_first=False, dtype=None, ): """Convert categorical variable into indicator variables. Args: data (array-like, Series, or DataFrame): data to encode. prefix (strin...
Applies func to the object in the plasma store.
def apply( self, func, num_splits=None, other_axis_partition=None, maintain_partitioning=True, **kwargs ): """Applies func to the object in the plasma store. See notes in Parent class about this method. Args: func: The function to...
Shuffle the order of the data in this axis based on the lengths.
def shuffle(self, func, lengths, **kwargs): """Shuffle the order of the data in this axis based on the `lengths`. Extends `BaseFrameAxisPartition.shuffle`. Args: func: The function to apply before splitting. lengths: The list of partition lengths to split the result int...
Deploy a function along a full axis in Ray.
def deploy_axis_func( cls, axis, func, num_splits, kwargs, maintain_partitioning, *partitions ): """Deploy a function along a full axis in Ray. Args: axis: The axis to perform the function along. func: The function to perform. num_splits: ...
Deploy a function along a full axis between two data sets in Ray.
def deploy_func_between_two_axis_partitions( cls, axis, func, num_splits, len_of_left, kwargs, *partitions ): """Deploy a function along a full axis between two data sets in Ray. Args: axis: The axis to perform the function along. func: The function to perform. ...
Query columns of the DataManager with a boolean expression. Args: expr: Boolean expression to query the columns with. Returns: DataManager containing the rows where the boolean expression is satisfied.
def query(self, expr, **kwargs): """Query columns of the DataManager with a boolean expression. Args: expr: Boolean expression to query the columns with. Returns: DataManager containing the rows where the boolean expression is satisfied. """ d...
Converts Modin DataFrame to Pandas DataFrame. Returns: Pandas DataFrame of the DataManager.
def to_pandas(self): """Converts Modin DataFrame to Pandas DataFrame. Returns: Pandas DataFrame of the DataManager. """ df = self.data.to_pandas(is_transposed=self._is_transposed) if df.empty: dtype_dict = { col_name: pandas.Serie...
Deploy a function along a full axis in Ray.
def deploy_ray_axis_func(axis, func, num_splits, kwargs, *partitions): """Deploy a function along a full axis in Ray. Args: axis: The axis to perform the function along. func: The function to perform. num_splits: The number of splits to return (see `split_result_of_axis_func...
Deploy a function along a full axis between two data sets in Ray.
def deploy_ray_func_between_two_axis_partitions( axis, func, num_splits, len_of_left, kwargs, *partitions ): """Deploy a function along a full axis between two data sets in Ray. Args: axis: The axis to perform the function along. func: The function to perform. num_splits: The number...
Applies func to the object in the plasma store.
def apply(self, func, num_splits=None, other_axis_partition=None, **kwargs): """Applies func to the object in the plasma store. See notes in Parent class about this method. Args: func: The function to apply. num_splits: The number of times to split the result object. ...
Shuffle the order of the data in this axis based on the func.
def shuffle(self, func, num_splits=None, **kwargs): """Shuffle the order of the data in this axis based on the `func`. Extends `BaseFrameAxisPartition.shuffle`. :param func: :param num_splits: :param kwargs: :return: """ if num_splits is None: ...
Deploy a function to a partition in Ray.
def deploy_ray_func(func, partition, kwargs): """Deploy a function to a partition in Ray. Args: func: The function to apply. partition: The partition to apply the function to. kwargs: A dictionary of keyword arguments for the function. Returns: The result of the function. ...
Gets the object out of the plasma store.
def get(self): """Gets the object out of the plasma store. Returns: The object from the plasma store. """ if len(self.call_queue): return self.apply(lambda x: x).get() return ray.get(self.oid)
Apply a function to the object stored in this partition.
def apply(self, func, **kwargs): """Apply a function to the object stored in this partition. Note: It does not matter if func is callable or an ObjectID. Ray will handle it correctly either way. The keyword arguments are sent as a dictionary. Args: func: The...
Convert the object stored in this partition to a Pandas DataFrame.
def to_pandas(self): """Convert the object stored in this partition to a Pandas DataFrame. Returns: A Pandas DataFrame. """ dataframe = self.get().to_pandas() assert type(dataframe) is pandas.DataFrame or type(dataframe) is pandas.Series return dataframe
Put an object in the Plasma store and wrap it in this object.
def put(cls, obj): """Put an object in the Plasma store and wrap it in this object. Args: obj: The object to be put. Returns: A `RayRemotePartition` object. """ return PyarrowOnRayFramePartition(ray.put(pyarrow.Table.from_pandas(obj)))
Detect missing values for an array - like object. Args: obj: Object to check for null or missing values.
def isna(obj): """ Detect missing values for an array-like object. Args: obj: Object to check for null or missing values. Returns: bool or array-like of bool """ if isinstance(obj, BasePandasDataset): return obj.isna() else: return pandas.isna(obj)
Database style join where common columns in on are merged.
def merge( left, right, how="inner", on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=("_x", "_y"), copy=True, indicator=False, validate=None, ): """Database style join, where common columns in "on" are merged. A...
Check if is possible distribute a query given that args
def is_distributed(partition_column, lower_bound, upper_bound): """ Check if is possible distribute a query given that args Args: partition_column: column used to share the data between the workers lower_bound: the minimum value to be requested from the partition_column upper_bound: the...
Check with the given sql arg is query or table
def is_table(engine, sql): """ Check with the given sql arg is query or table Args: engine: SQLAlchemy connection engine sql: SQL query or table name Returns: True for table or False if not """ if engine.dialect.has_table(engine, sql): return True return False
Extract all useful infos from the given table
def get_table_metadata(engine, table): """ Extract all useful infos from the given table Args: engine: SQLAlchemy connection engine table: table name Returns: Dictionary of infos """ metadata = MetaData() metadata.reflect(bind=engine, only=[table]) table_metadata = ...