Search is not available for this dataset
text
stringlengths
75
104k
def get_default_sess_config(mem_fraction=0.99): """ Return a tf.ConfigProto to use as default session config. You can modify the returned config to fit your needs. Args: mem_fraction(float): see the `per_process_gpu_memory_fraction` option in TensorFlow's GPUOptions protobuf: ...
def get_global_step_var(): """ Returns: tf.Tensor: the global_step variable in the current graph. Create if doesn't exist. """ scope = tfv1.VariableScope(reuse=False, name='') # the root vs with tfv1.variable_scope(scope): var = tfv1.train.get_or_create_global_step() return var
def get_tensors_by_names(names): """ Get a list of tensors in the default graph by a list of names. Args: names (list): """ ret = [] G = tfv1.get_default_graph() for n in names: opn, varn = get_op_tensor_name(n) ret.append(G.get_tensor_by_name(varn)) return ret
def get_op_or_tensor_by_name(name): """ Get either tf.Operation of tf.Tensor from names. Args: name (list[str] or str): names of operations or tensors. Raises: KeyError, if the name doesn't exist """ G = tfv1.get_default_graph() def f(n): if len(n) >= 3 and n[-2] =...
def collect_env_info(): """ Returns: str - a table contains important information about the environment """ data = [] data.append(("sys.platform", sys.platform)) data.append(("Python", sys.version.replace("\n", ""))) data.append(("Tensorpack", __git_version__)) data.append(("Nump...
def _add_sync_queues_and_barrier(self, name, dependencies): """Adds ops to enqueue on all worker queues. Args: name: prefixed for the shared_name of ops. dependencies: control dependency from ops. Returns: an op that should be used as control dependency befo...
def _apply_shadow_vars(avg_grads): """ Create shadow variables on PS, and replace variables in avg_grads by these shadow variables. Args: avg_grads: list of (grad, var) tuples """ ps_var_grads = [] for grad, var in avg_grads: assert var.na...
def _shadow_model_variables(shadow_vars): """ Create shadow vars for model_variables as well, and add to the list of ``shadow_vars``. Returns: list of (shadow_model_var, local_model_var) used for syncing. """ G = tf.get_default_graph() curr_shadow_vars = set(...
def build(self, get_grad_fn, get_opt_fn): """ Args: get_grad_fn (-> [(grad, var)]): get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer Returns: (tf.Operation, tf.Operation, tf.Operation): 1. the training op. 2. t...
def _apply_gradients_and_copy(self, opt, raw_grad_list, ps_var_grads): """ Apply averaged gradients to ps vars, and then copy the updated variables back to each tower. Args: raw_grad_list: Ngpu x Nvar x 2 gradient list from all towers ps_var_grads: Nvar x 2 (grad...
def _get_initial_sync_op(self): """ Get the op to copy-initialized all local variables from PS. """ def strip_port(s): if s.endswith(':0'): return s[:-2] return s local_vars = tf.local_variables() local_var_by_name = dict([(strip_po...
def _get_sync_model_vars_op(self): """ Get the op to sync local model_variables to PS. """ ops = [] for (shadow_v, local_v) in self._shadow_model_vars: ops.append(shadow_v.assign(local_v.read_value())) assert len(ops) return tf.group(*ops, name='sync_{...
def get_tensors_inputs(placeholders, tensors, names): """ Args: placeholders (list[Tensor]): tensors (list[Tensor]): list of tf.Tensor names (list[str]): names matching the given tensors Returns: list[Tensor]: inputs to used for the tower function, with the corre...
def get_sublist_by_names(lst, names): """ Args: lst (list): list of objects with "name" property. Returns: list: a sublist of objects, matching names """ orig_names = [p.name for p in lst] ret = [] for name in names: try: idx = orig_names.index(name) ...
def remap_input_source(input, names): """ When you have some :class:`InputSource` which doesn't match the inputs of your tower function, use `RemapInputSource`. It produces placeholders for all the inputs in your model, except that the corresponding ones are replaced with the tensor produced by ...
def rpn_head(featuremap, channel, num_anchors): """ Returns: label_logits: fHxfWxNA box_logits: fHxfWxNAx4 """ with argscope(Conv2D, data_format='channels_first', kernel_initializer=tf.random_normal_initializer(stddev=0.01)): hidden = Conv2D('conv0', featuremap,...
def rpn_losses(anchor_labels, anchor_boxes, label_logits, box_logits): """ Args: anchor_labels: fHxfWxNA anchor_boxes: fHxfWxNAx4, encoded label_logits: fHxfWxNA box_logits: fHxfWxNAx4 Returns: label_loss, box_loss """ with tf.device('/cpu:0'): valid...
def generate_rpn_proposals(boxes, scores, img_shape, pre_nms_topk, post_nms_topk=None): """ Sample RPN proposals by the following steps: 1. Pick top k1 by scores 2. NMS them 3. Pick top k2 by scores. Default k2 == k1, i.e. does not filter the NMS output. Args: ...
def MergeAllSummaries(period=0, run_alone=False, key=None): """ This callback is enabled by default. Evaluate all summaries by ``tf.summary.merge_all``, and write them to logs. Args: period (int): by default the callback summarizes once every epoch. This option (if not set to 0) mak...
def append(self, exp): """ Args: exp (Experience): """ if self._curr_size < self.max_size: self._assign(self._curr_pos, exp) self._curr_pos = (self._curr_pos + 1) % self.max_size self._curr_size += 1 else: self._assign(s...
def sample(self, idx): """ return a tuple of (s,r,a,o), where s is of shape self._output_shape, which is [H, W, (hist_len+1) * channel] if input is (H, W, channel)""" idx = (self._curr_pos + idx) % self._curr_size k = self.history_len + 1 if idx + k <= self._curr_...
def step(self, exploration): """ Run the environment for one step. If the episode ends, store the entire episode to the replay memory. """ old_s = self._current_ob if self.rng.rand() <= exploration: act = self.rng.choice(range(self.num_actions)) else: ...
def recent_state(self): """ Get the recent state (with stacked history) of the environment. Returns: a list of ``hist_len-1`` elements, each of shape ``self.state_shape`` """ expected_len = self.history_len - 1 if len(self._current_episode) >= expected_len: ...
def step(self, exploration): """ Execute one step in any of the runners. """ if len(self._runners) > 1: self._populate_job_queue.put(exploration) else: self._runners[0].step(exploration)
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: ...
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...
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: .. ...
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)
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)
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...
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_...
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=.....
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...
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(...
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)
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...
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...
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)
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]
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_...
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...
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 = ...
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...
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: ...
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...
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...
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...
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 ...
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. ....
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 ...
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 ...
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 ...
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...
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 ...
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 ...
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) ...
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...
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)...
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...
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...
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 ...
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...
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...
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...
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 ...
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
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)]
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...
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. ...
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 ...
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] ...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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. ...
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] ...
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, ...
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 ...
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...
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 ...
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...
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...
def fg_box_logits(self): """ Returns: #fg x ? x 4 """ return tf.gather(self.box_logits, self.proposals.fg_inds(), name='fg_box_logits')
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, ...
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...
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)
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...
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...
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) ...
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...
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...
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...
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, ): ...
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: ...